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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19838206/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 16:59:47  来源:igfitidea点击:

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

javascripttoggle

提问by Cindy Turlington

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”行将消失,现在我必须单击“单击此处”使其消失。

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

回答by giaour

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

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

回答by merezha

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');
};

回答by Mageek

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/