简体   繁体   English

单击页面的其余部分时如何使javascript对象消失

[英]how to make javascript object disappear when click on rest of page

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. 如何更改以下代码,以便在单击网页上的任意位置时,“ This is foo”行将消失,现在我必须单击“ Click here”使其消失。

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

您需要将click事件绑定到body元素,以便在单击页面上的任意位置时触发它。

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: 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: 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: 这一点的CSS:

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

http://jsfiddle.net/57ZpS/8/ http://jsfiddle.net/57ZpS/8/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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