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>
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>
Share
Improve this question
asked Nov 7, 2013 at 14:18
Cindy TurlingtonCindy Turlington
2,5273 gold badges18 silver badges21 bronze badges
1
-
you may wish to use something other than an
<a>
tag for a button, otherwise you need apreventDefault();
mechanism in your function or a hack likeonclick="toggle_visibility('foo');return false;"
– technosaurus Commented Nov 7, 2013 at 14:56
3 Answers
Reset to default 1You'll need to bind the click event to the body
element for it to fire when you click anywhere on the page.
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%;
}
http://jsfiddle/57ZpS/8/
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745162868a4614474.html
评论列表(0条)