简体   繁体   中英

How to hide or show div on click?

I'm trying to create a button which will show a div if it is hidden, or hide the div if it is already shown (doing it in javascript). I've written this code to be used onclick but it doesn't seem to work and I can't see why. Can someone see what I have done wrong?

if (document.getElementById('Hidey').style.display == 'none') {
document.getElementById('Hidey').style.display = 'inline'
}
else {
document.getElementById('Hidey').style.display = 'none'
}

EDIT: HTML

<div id="Button" onclick="javascript posted above here"><h2>Click</h2></div>
<div id="Hidey">Content Inside</div>

That's the HTML being effected, nothing else in my code effects these. I'm simply confused.

I've set up a plunker here http://plnkr.co/edit/EkuW8nEIV22vmuaDM9JR?p=preview .

<script>
  var toggle = function(){
    if (document.getElementById('Hidey').style.display == 'none') {
      document.getElementById('Hidey').style.display = 'inline'
    }
    else {
      document.getElementById('Hidey').style.display = 'none'
    }
  }

</script>

<h1 id="Hidey">Hello Plunker!</h1>
<a href="#" onclick="toggle()">click me</a>

Your code seems good. I think you maybe weren't setting up the function correctly or calling the function correctly.

使用 jQuery 并使用这个:

$("button").onclick( function() {("#Hidey").toggle();});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM