显示/隐藏div的按钮必须按两次 [英] Button to show/hide div has to be pressed twice

查看:80
本文介绍了显示/隐藏div的按钮必须按两次的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的目标:仅在页面上隐藏我的div,并仅使用HTML/CSS/JavaScript使用按钮显示/隐藏div.

My Goal: to have my div hidden on page load and show/hide the div with a button using only HTML/CSS/JavaScript.

我已经在HTML和JavaScript中设置了一个按钮来显示/隐藏我的div,当div在页面加载时可见并且不使用CSS隐藏时,该按钮非常有用.当我使用CSS显示隐藏div时:none;div在页面加载时是隐藏的,但必须先单击两次按钮才能使div可见.

I have set up a button in HTML and JavaScript to show/hide my div which works great when the div is visible on page load and not hidden using CSS. When I hide the div using CSS display: none; the div is hidden on page load but the button has to be clicked twice before the div becomes visible.

HTML:

  <button class="btn btn-link" id="btnLink" onclick="hideLink()">Hide 
  Content</button> <br><br>
  <div id="myLink">
  <h1>Div content here</h1>
  </div>

CSS:

#myLink {display:none;}

#myLink {display: none;}

JavaScript:

JavaScript:

function hideLink() {
var x = document.getElementById('myLink');
var b = document.getElementById('btnLink');


if (x.style.display === 'none') {
    x.style.display = 'block';
    b.childNodes[0].nodeValue="Hide Content";

} else {
    x.style.display = 'none';
    b.childNodes[0].nodeValue="Show Content";
}
}

推荐答案

您应该检查!=='block',而不是 ==='none'

当我们在CSS中使用 none 时,将 x.style.display 的值设置为空白,因为css选择器将获得 none 而不是元素的属性(至少是我所了解的).因此,检查 === none 实际上比较它会为空,并返回false( x.style.display ='').

The value x.style.display is set to blank when we use none in the css as the css selector is what gets the none attribute than the element ( at lease that is what I understand ). So the check === none actually compares it will blank and return false ( x.style.display = '').

现在,一旦我们使用JS将值设置为 block ,元素的 style.display 属性就具有一个可以比较的值.

Now once we have set the value to block using JS the element's style.display property has a value which we can compare.

function hideLink() {
  var x = document.getElementById('myLink');
  var b = document.getElementById('btnLink');


  if (x.style.display !== 'block') {
    x.style.display = 'block';
    b.childNodes[0].nodeValue = "Hide Content";

  } else {
    x.style.display = 'none';
    b.childNodes[0].nodeValue = "Show Content";
  }
}

#myLink {
  display: none;
}

<button class="btn btn-link" id="btnLink" onclick="hideLink()">
Show Content
</button>
<br><br>
<div id="myLink">
  <h1>Div content here</h1>
</div>

这篇关于显示/隐藏div的按钮必须按两次的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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