簡體   English   中英

單擊頁面的其余部分時如何使javascript對象消失

[英]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%;
}

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM