首页 > 解决方案 > 如何将 DIV 默认设置为 style.display = "none"?

问题描述

我正在尝试制作一个按钮,当它被点击时会显示其他文本,但是,我只能制作它

这是按钮的JS代码:

function showInfo() {
  var x = document.getElementById("myDIV");
  
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<div id="myDIV">
 Hello World
</div>
<button type="button" class="btn btn-primary" click="showInfo()">
Show Info
</button>

有没有办法可以将默认 style.display 设置为 none?

标签: javascripthtmlcssbuttonhidden

解决方案


你的处理程序是click. 它需要是onclick。另外,我建议您添加一个带有的类display:nonediv或者简单地内联它,如下所示:

<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
<div id="myDIV" style="display: none">
 Hello World
</div>
<button onclick="showInfo()">
Show Info
</button>

然后你的 JS 可以如下所示:

function showInfo() {
  var x = document.getElementById("myDIV");
  if (x.style.display === "none") {
    return x.style.display = "block";
  }
  return x.style.display = "none";
}

演示

function showInfo() {
  var x = document.getElementById("myDIV");
  if (x.style.display === "none") {
    return x.style.display = "block";
  }
  return x.style.display = "none";
}
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" rel="stylesheet"/>
    <div id="myDIV" style="display: none">
     Hello World
    </div>
    <button onclick="showInfo()">
    Show Info
    </button>


推荐阅读