【问题标题】:Hide and show buttons need to be "show" first隐藏和显示按钮需要先“显示”
【发布时间】:2018-07-31 20:37:28
【问题描述】:

我想制作一些显示/隐藏按钮,但我需要先使元素不可见,并且仅在按下按钮后才可见 - 与现在相反:

function myFunction(x) {
  x.classList.toggle("change");
  var x = document.getElementById("navigationList");

  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
}
<div class="navigation_bar">
  <button class="hamburger" onclick="myFunction(this)">
    	    <div class="bar1"></div>
    	    <div class="bar2"></div>
	    </button>
  <div id="navigationList">
    <ul>
      <li><a class="active" href="home_1_t.html">home</a></li>
      <li><a href="coming soon.html">about</a></li>
      <li><a href="coming soon.html">products</a></li>
      <li><a href="coming soon.html">services</a></li>
      <li><a href="coming soon.html">contact</a></li>
    </ul>
  </div>

【问题讨论】:

    标签: html css button toggle show


    【解决方案1】:

    在css中,首先将#navigationList设为none,如下所示:

    <style>#navigationList{display:none;} </style>
    
    <script>
    
    function myFunction(x) {
    
       x.classList.toggle("change");
    
       var x = document.getElementById("navigationList");
    
        if (x.style.display === "block") {
    
          x.style.display = "none";
    
        } else {
    
           x.style.display = "block";  
          }
    
      }
    
    </script>
    

    【讨论】:

      【解决方案2】:

      这应该是工作:

      function myFunction() {
        var x = document.getElementById("navigationList");
        if (x.style.display === "none") {
          x.style.display = "block";
        } else {
          x.style.display = "none";
        }
      }
      <div class="navigation_bar">
        <!-- had to correct a mistyped class name -->
        <button class="hamburger" onclick="myFunction()">Toggle-Button</button>
        <!-- the parameter "x" is not needed here -->
        <div class="bar1"></div>
        <div class="bar2"></div>
        </button>
        <div id="navigationList" style="display: none;">
          <ul>
            <li><a class="active" href="home_1_t.html">home</a></li>
            <li><a href="coming soon.html">about</a></li>
            <li><a href="coming soon.html">products</a></li>
            <li><a href="coming soon.html">services</a></li>
            <li><a href="coming soon.html">contact</a></li>
          </ul>
        </div>

      【讨论】:

      • 您的初始点击将不起作用,因为没有要检查的样式属性。因此它会在第一次失败。
      • 完全忘记了!谢谢,我更正了我的答案。 @ARJUN
      【解决方案3】:

      只需在导航列表中放置一个值为“display: none”的样式属性。

      此外,您只检查字符串,因此“==”(双等号)应该有效,而不是“===”。

      <div id="navigationList" style="display : none;">
      
      </div>
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-06-05
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-03-31
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多