admin管理员组

文章数量:1414628

How to change the following code so when clicking anywhere on the web page, the line "This is foo" will disappear, right now I have to click "Click here" to make it disappear.

<html>
<script type="text/javascript">
<!--
    function toggle_visibility(id) {
       var e = document.getElementById(id);
       if(e.style.display == 'block')
          e.style.display = 'none';
       else
          e.style.display = 'block';
    }
//-->
</script>
<body>
<a href="#" onclick="toggle_visibility('foo');">Click here</a>
<div id="foo">This is foo</div>
</body>
</html>

How to change the following code so when clicking anywhere on the web page, the line "This is foo" will disappear, right now I have to click "Click here" to make it disappear.

<html>
<script type="text/javascript">
<!--
    function toggle_visibility(id) {
       var e = document.getElementById(id);
       if(e.style.display == 'block')
          e.style.display = 'none';
       else
          e.style.display = 'block';
    }
//-->
</script>
<body>
<a href="#" onclick="toggle_visibility('foo');">Click here</a>
<div id="foo">This is foo</div>
</body>
</html>
Share Improve this question asked Nov 7, 2013 at 14:18 Cindy TurlingtonCindy Turlington 2,5273 gold badges18 silver badges21 bronze badges 1
  • you may wish to use something other than an <a> tag for a button, otherwise you need a preventDefault(); mechanism in your function or a hack like onclick="toggle_visibility('foo');return false;" – technosaurus Commented Nov 7, 2013 at 14:56
Add a ment  | 

3 Answers 3

Reset to default 1

You'll need to bind the click event to the body element for it to fire when you click anywhere on the page.

Try to use document object for attaching event handler

document.onclick = function(){
   var e = document.getElementById('foo');
   e.style.display = ((e.style.display != 'none') ? 'none' : 'block');
};

HTML:

<body onclick="foo();">
<a href="#" onclick="toggle_visibility('foo');">Click here</a>

    <div id="foo" style="display:none;" >This is foo</div>
</body>

JS:

var b = false;

function toggle_visibility(id) {
    var e = document.getElementById(id);
     if(e.style.display == 'block')
          e.style.display = 'none';
       else
          e.style.display = 'block';
    b = true;
}

function foo() {
    var e = document.getElementById('foo');
    if(!b) e.style.display = 'none';
    b=false;
}

And this bit of css:

body,html
{
    width:100%;
    height:100%;
}

http://jsfiddle/57ZpS/8/

本文标签: togglehow to make javascript object disappear when click on rest of pageStack Overflow