[英]how to make javascript object disappear when click on rest of page
如何更改以下代碼,以便在單擊網頁上的任意位置時,“ 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
元素,以便在單擊頁面上的任意位置時觸發它。
嘗試使用文檔對象附加事件處理程序
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;
}
這一點的CSS:
body,html
{
width:100%;
height:100%;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.