【问题标题】:Why my show hide button needs double-click on first time为什么我的显示隐藏按钮第一次需要双击
【发布时间】:2019-07-30 23:39:56
【问题描述】:

我的网站上有这个显示/隐藏按钮。它可以工作,但用户第一次需要双击它,好像开关设置为“隐藏”但元素已经隐藏了......

我想编辑我的代码,以便按钮在第一次单击时显示元素

我是 javascript 新手,所以我不知道如何更改它。

谢谢

function showhidemenu() {
  var x = document.getElementById("menu");
  if (x.style.display === "none") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
}
#menu {
  background: rgba(0, 0, 0, 0);
  position: absolute;
  z-index: 1;
  top: 60px;
  right: 50px;
  width: 150px;
  font-family: 'Open Sans', sans-serif;
  display: none;
}
<div id="menu">This is a menu</div>
<button onclick="showhidemenu()">Show/hide</button>

【问题讨论】:

  • 这样的事情是你应该直接检查 CSS 属性的原因。使用颜色值更难正确处理。相反,应该使用 CSS 类,例如#menu.hidden { display: none; };然后应该检查x.classList.has("hidden")。或者干脆使用hidden attribute

标签: javascript html css button show-hide


【解决方案1】:

为了达到预期的效果,请使用下面的选项检查初始显示,如果不是内联则为空

x.style.display === "none" || x.style.display === ""

更多详情请参考此链接 - Why element.style always return empty while providing styles in CSS?

function showhidemenu() {
  var x = document.getElementById("menu");
  if (x.style.display === "none" || x.style.display === "") {
    x.style.display = "block";
  } else {
    x.style.display = "none";
  }
}
#menu {
  background: rgba(0, 0, 0, 0);
  position: absolute;
  z-index: 1;
  top: 60px;
  right: 50px;
  width: 150px;
  font-family: 'Open Sans', sans-serif;
  display: none;
}
<div id="menu">This is a menu</div>
<button onclick="showhidemenu()">Show/hide</button>

【讨论】:

    【解决方案2】:

    因为最初 x.style.display === "none"false 并且它转到 else 块。
    为此,您可以使用三元运算符

    function showhidemenu() {
      var x = document.getElementById("menu");
      x.style.display = !x.style.display ? 'block' : '';
    }
    #menu {
      background: rgba(0, 0, 0, 0);
      position: absolute;
      z-index: 1;
      top: 60px;
      right: 50px;
      width: 150px;
      font-family: 'Open Sans', sans-serif;
      display: none;
    }
    <div id="menu">This is a menu</div>
    <button onclick="showhidemenu()">Show/hide</button>

    代码有效,因为'' 是假值

    【讨论】:

      【解决方案3】:

      您需要检查您的“if/then”语句。您正在检查错误的顺序。

      function showhidemenu() {
        var x = document.getElementById("menu");
        if (x.style.display == "block") {
          x.style.display = "none";
        } else {
          x.style.display = "block";
        }
      }
      #menu {
        background: rgba(0, 0, 0, 0);
        position: absolute;
        z-index: 1;
        top: 60px;
        right: 50px;
        width: 150px;
        font-family: 'Open Sans', sans-serif;
        display: none;
      }
      <div id="menu">This is a menu</div>
      <button onclick="showhidemenu()">Show/hide</button>

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-07-31
        • 2017-08-06
        • 2018-06-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-03-15
        • 1970-01-01
        相关资源
        最近更新 更多