显示/隐藏谷歌地图 API 无法正常工作



当我点击这个按钮时,我希望值发生变化。当我这样做时,起初它会更改按钮上的文本,但地图没有出现。之后,我重复该过程,代码工作正常。

function change() {
var elem = document.getElementById("myButton1");
if (elem.value == "Show") elem.value = "Hide";
else elem.value = "Show";
}
function displayMap() {
if (document.getElementById('map').style.display == "none") {
document.getElementById('map').style.display = "block";
initialize();
} else {
document.getElementById('map').style.display = "none";
}
}
#map {
display: none;
}
<input onclick='change(), displayMap()' type='button' value='Show' id='myButton1'></input>
<div id="map" style="width:100%; height:300px;">map</div>

全局

分配document.getElementById('map').style.display = "none";

请尝试下面的代码

document.getElementById('map').style.display = "none";// this line is the solution 
function change() {
var elem = document.getElementById("myButton1");
if (elem.value == "Show") elem.value = "Hide";
else elem.value = "Show";           
}
function displayMap() {
if (document.getElementById('map').style.display === "none")       {
document.getElementById('map').style.display = "block";
} else {
document.getElementById('map').style.display = "none";
}
}

#map {
display: none;
}
<input onclick='change(), displayMap()' type='button' value='Show' id='myButton1'></input>
<div id="map" style="width:100%; height:300px;">map</div>

注意:不要忘记调用从我的代码段中删除的initialize()函数

>HTMLElement.style返回内联样式(style属性中列出的样式(。

你可以像这样使用Window.getComputedStyle()

var map = document.getElementById('map'),
btn = document.getElementById("myButton1");
function change() {
if (btn.value == "Show") btn.value = "Hide";
else btn.value = "Show";
}
function displayMap() {
var style = window.getComputedStyle(map);
if (style.display == "none") {
map.style.display = "block";
initialize();
} else {
map.style.display = "none";

console.log('hiding');
}
}
// Placeholder
function initialize() {
console.log('showing map');
}
#map {
display: none;
width: 100%;
height: 300px;
background:#333;
}
<input onclick='change(), displayMap()' type='button' value='Show' id='myButton1' />
<div id="map"></div>

上面的方法很好,但我会使用更一致的方法,例如 CSS 类,并且我会首先初始化映射,因为您的实现方式耗尽了initialize()

最新更新