最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - Toggle visibility of an element with JavaScript - Stack Overflow

programmeradmin0浏览0评论

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>

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>

Share Improve this question asked Dec 4, 2015 at 21:17 Garland BriggsGarland Briggs 1192 silver badges13 bronze badges 3
  • #foo { display: none; } – user2417483 Commented Dec 4, 2015 at 21:19
  • So you want #foo to be invisible when you load the page? – redeagle47 Commented Dec 4, 2015 at 21:27
  • No, not necessarily. Rick Hitchcock pointed me in the right direction. – Garland Briggs Commented Dec 4, 2015 at 22:57
Add a ment  | 

1 Answer 1

Reset to default 9

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>

发布评论

评论列表(0)

  1. 暂无评论