Toggle visibility of an element with JavaScript

时间:2015-12-04 21:18:00

标签: javascript html css

Trying to toggle the visibility of an element with JavaScript. It's working, but I have to click once first, which of course isn't optimal. Can someone point out to me why this isn't working properly?

function toggle_visibility(id) {
  var e = document.getElementById(id);
  if(e.style.display == 'block')
    e.style.display = 'none';
  else
    e.style.display = 'block';
}
#foo {
  display: block;
}
<a href="#" onclick="toggle_visibility('foo');">Click here to toggle visibility of element #foo</a>
<div id="foo">This is foo</div>

1 个答案:

答案 0 :(得分:7)

Reverse your if and else tests. JavaScript can't read CSS properties from style unless it explicitly sets them:

function toggle_visibility(id) {
  var e = document.getElementById(id);
  if(e.style.display == 'none')
    e.style.display = 'block';
  else
    e.style.display = 'none';
}
#foo {
  display: block;
}
<a href="#" onclick="toggle_visibility('foo');">Click here to toggle visibility of element #foo</a>
<div id="foo">This is foo</div>