单击同一按钮时如何显示或隐藏 div?

How to show or hide a div when clicking on the same button?

当我想在传单地图上添加交互时遇到问题。

我的地图上有一个按钮

<button id="az">Availability Zones</button>

我想要的是当我点击它时,它会在我的地图上显示一个方形的信息 所以我创建了一个正方形

<div class="square" id='square'> </div> 
CSS = .square{
  z-index: 4000;
   width: 100%;
  height: 0;
  padding-top: 100%;
  background-color: #ccc;
  position: absolute;
  display: none;
}

还有另一个 css class 具有相同属性但显示为:块

的正方形
.squareclick{
  z-index: 4000;
   width: 30%;
  weight: 30%;
  padding: 0 25 30;
  margin-left: 400px;
  margin-bottom: 200px;
  height: 0;
  padding-top: 100%;
  background-color: #ccc;
  position: relative;
  display: block;
}

现在,为了在按钮上打开这个方块,我添加了一些交互性

var button = document.getElementById('az')
L.DomEvent.on(button,'click',function(e){
    console.log('Button clicked')
});

L.DomEvent.on(button,'click',function(){
    document.getElementById('square').setAttribute("class", "squareclick");
  
});

问题是那个按钮用于打开正方形,但不能用于关闭(我知道这是正常的) 我试过那个东西,但它似乎不起作用

L.DomEvent.on(button,'click',function myFunction() {
  var x = document.getElementById("square");
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }

我不知道如何在同一个按钮上添加第二个交互性:(

如果有人能帮忙! 非常感谢

您可以尝试做的不是直接检查正方形是否可见,而是可以设置一个变量来检查。变化:

L.DomEvent.on(button,'click',function myFunction() {
  var x = document.getElementById("square");
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
}

收件人:

var shown = false;    

L.DomEvent.on(button,'click',function myFunction() {
  var x = document.getElementById("square");
  if (shown == false) {
    x.style.display = "block";
    shown = true;
  } else if (shown == true) {
    x.style.display = "none";
    shown = false;
  }
}

变量shown告诉我们一开始这个方块是不可见的。每次单击按钮时,变量都会更改,样式也会更改。如果正方形在开始时可见,那么您只需在脚本开始时将 shown 更改为 true 即可。看看这种方法是否有效。 :)

我建议只在改变display: none样式的方块中添加一个class。

var button = document.getElementById('az')
var square = document.getElementById('square')
L.DomEvent.on(button,'click',function(e){
    console.log('Button clicked')
    if(L.DomUtil.hasClass(square,'show')){
        L.DomUtil.removeClass(square,'show');
    }else{
        L.DomUtil.addClass(square,'show');
    }
});
.square{
  z-index: 4000;
   width: 30%;
  weight: 30%;
  padding: 0 25 30;
  margin-left: 400px;
  margin-bottom: 200px;
  height: 0;
  padding-top: 100%;
  background-color: #ccc;
  position: absolute;
  display: none;
}

.show{
  display: block;
}

https://jsfiddle.net/falkedesign/v8tdzmhe/