【问题标题】:I want to make an element display when a button is pressed. by default the element is shown, how do I make it display none by default?我想在按下按钮时显示元素。默认情况下显示元素,如何使其默认不显示?
【发布时间】:2019-08-14 04:03:34
【问题描述】:

按钮的所有内容似乎都是正确的,并且与我目前想要的相反。当我加载页面时, div: myDIV 就在那里,并且按钮将其切换为消失和重新出现。如何使 myDIV 默认为无但仍具有按钮功能作为切换

<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
#myDIV {
  width: 100%;
  padding: 50px 0;
  text-align: center;
  background-color: lightblue;
  margin-top: 20px;
  display:none;
}
</style>
</head>
<body>


<button onclick="myFunction()">test</button>

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



<script>
function myFunction() {
  var x = document.getElementById("myDIV");
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
}
</script>

</body>
</html>

【问题讨论】:

  • 添加样式display:none到div chartContainer
  • 我已经尝试过了,这只是意味着我必须单击按钮两次才能显示 div :)
  • 按钮在哪里消失和重新出现?
  • 那么,您创建了&lt;div id="myDIV" style="display:none"&gt;,但您的代码不起作用?也许您应该显示 real 代码,因为根据第一条评论添加样式会起作用(我注意到您已经更改了问题中的代码以使第一条评论看起来很荒谬,但是,评论100% 正确)

标签: javascript css button hide


【解决方案1】:

我认为重点在这里style.display = '' actually do

使用style.display获取显示状态时,无法获取css中定义的显示属性

【讨论】:

    【解决方案2】:

    您需要先获取 CSS 值才能在 JS 中使用按钮切换显示值。默认情况下,建议不要在 HTML 上提供内联样式。

    function myFunction() {
    	const cont = document.querySelector("#chartContainer");
    	const styles = getComputedStyle(cont)
      const displayStyle = styles.display;
      if(displayStyle === "none"){
      	cont.style.display = "block";
      }else {
      	cont.style.display = "none";
      }
      
    }
    
    const BTN = document.querySelector("button");
    BTN.addEventListener('click', myFunction);
    .container {
      background-color: #FFF;
      width: 100vw;
      height: 100vh;
      margin: 0;
      padding: 0;
      display: flex;
    }
    
    #chartContainer {
      background-color: blue;
      border-radius: 25px;
      height: 200px;
      width: 100%;
      float: below;
      display: none;
    }
    
    button {
      width: 50px;
      height: 50px;
    }
    <div class="container">
        <button>toggle</button>
        <div id="chartContainer">
        </div>
        <script src="https://canvasjs.com/assets/script/canvasjs.min.js">	</script>
    </div>

    【讨论】:

      猜你喜欢
      • 2011-06-30
      • 1970-01-01
      • 2017-12-16
      • 2017-10-14
      • 1970-01-01
      • 1970-01-01
      • 2017-02-07
      • 1970-01-01
      • 2018-03-03
      相关资源
      最近更新 更多