为什么我的显示隐藏按钮第一次需要双击 [英] Why my show hide button needs double-click on first time

查看:21
本文介绍了为什么我的显示隐藏按钮第一次需要双击的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的网站上有这个显示/隐藏按钮.它有效,但第一次用户需要双击它,就好像开关设置为隐藏"但元素已经隐藏...

I have this show/hide button on my website. It works, but on the first time the user needs to double-click it as if the switch is set to "hide" but the element is already hidden...

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

I'd like to edit my code so the button shows the element with a single click on the first time

我是 JavaScript 新手,所以我不知道如何改变这一点.

I'm new to javascript, so I don't know how to change this.

谢谢

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>

推荐答案

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

To achieve expected result, use below option of checking display initially which will be empty if it is not inline

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

请参阅此链接了解更多详情 - 为什么在 CSS 中提供样式时 element.style 总是返回空?

Please refer this link for more details - 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>

这篇关于为什么我的显示隐藏按钮第一次需要双击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆