简体   繁体   中英

Show/Hide google maps api does not work fine

When I click on this button, I want the value to change. When I do it, at first it changes the text on button, but the map does not appear. after that, I repeat the process and the code works fine.

 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> 

Assign document.getElementById('map').style.display = "none"; globally

Please try this below code

  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> 

Note: Don't forgot to call your initialize() function which is removed from my snippet

HTMLElement.style returns the inline style (what is listed in the style attribute).

You could use Window.getComputedStyle() like this:

 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> 

Above method is fine, but I would a more consistent method such as a CSS class, and I would initialize the map in the first place because the way you implemented exhausts the initialize()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM