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>
您需要将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:
<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%;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.