Button to show/hide div has to be pressed twice

末鹿安然 提交于 2021-01-27 21:09:41

问题


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

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;}

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";
}
}

回答1:


You should check for !== 'block' rather than === 'none'

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 = '').

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>



回答2:


The first time the button is clicked, the element itself does not specifically have the style for display set. After your first if/then, then it does.

See here: http://plnkr.co/edit/4peCJS1vhJskexqdLdKL?p=preview

var t = document.getElementById('output').innerText;
document.getElementById('output').innerText = JSON.stringify(x.outerHTML);



回答3:


corrected it with another if...

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

if (x.style.display === ''){
    x.style.display = 'none';
}

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

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


来源:https://stackoverflow.com/questions/44837679/button-to-show-hide-div-has-to-be-pressed-twice

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!