首页 > 解决方案 > 想要使用布尔值显示和隐藏元素 true false

问题描述

我有 Div Container,我想通过单击按钮来显示和隐藏它。但我想使用 **Boolean True false 值

function myFunction() {
let booleanValue = true;
  var x = document.getElementById("myDIV");
  if (booleanValue === true) {
    x.style.display = "block";
    booleanValue = false;
  } else {
    x.style.display = "none";
  }
}
#myDIV {
  width: 100%;
  padding: 50px 0;
  text-align: center;
  background-color: lightblue;
  margin-top: 20px;
  display:none;
}
<button onclick="myFunction()">Try it</button>

<div id="myDIV">
This is my DIV element.
</div>

e**。

标签: javascript

解决方案


尝试使用全局变量。let booleanValue = true;与其在内部定义,不如myFunction在函数外部将其定义为全局变量。这样每次函数执行时,您都可以切换变量的值。

var booleanValue = true;
function myFunction() {
  booleanValue = !booleanValue;
  var x = document.getElementById("myDIV");
  if (booleanValue === true) {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
}
#myDIV {
  width: 100%;
  padding: 50px 0;
  text-align: center;
  background-color: lightblue;
  margin-top: 20px;
}
<button onclick="myFunction()">Toggle Div</button>
<div id="myDIV">
  This is my DIV element.
</div>


推荐阅读