js实现 点击元素以外的地方隐藏 元素的方法
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB2312" />
<title>点击一个连接显示层~点击其他区域隐藏 练习 by 脚本之家</title>
<style type="text/css">
#myDiv{
border:1px solid #000000;
width:200px;
height:100px;
background:#cccccc;
}
</style>
<script language="JavaScript" type="text/javascript">
function addListener(element, e, fn) {
if (element.addEventListener) {
element.addEventListener(e, fn, false);
} else {
element.attachEvent("on" + e, fn);
}
}
addListener(document, "click",
function(evt) {
var evt = window.event ? window.event: evt,
target = evt.srcElement || evt.target;
if (target.id == "showDiv") {
document.getElementById("myDiv").style.display = "";
return;
} else {
while (target.nodeName.toLowerCase() != "div" && target.nodeName.toLowerCase() != "html") {
target = target.parentNode;
}
if (target.nodeName.toLowerCase() == "html") {
document.getElementById("myDiv").style.display = "none";
}
}
})
</script>
</head>
<body>
<div id="myDiv" style="display:none;"><a href="http://www.jb51.net" target="_blank">脚本之家</a></div>
<input type="button" value="出来吧层" id="showDiv" />
</body>
</html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB2312" />
<title>点击一个连接显示层~点击其他区域隐藏 练习 by 脚本之家</title>
<style type="text/css">
#myDiv{
border:1px solid #000000;
width:200px;
height:100px;
background:#cccccc;
}
</style>
<script language="JavaScript" type="text/javascript">
function addListener(element, e, fn) {
if (element.addEventListener) {
element.addEventListener(e, fn, false);
} else {
element.attachEvent("on" + e, fn);
}
}
addListener(document, "click",
function(evt) {
var evt = window.event ? window.event: evt,
target = evt.srcElement || evt.target;
if (target.id == "showDiv") {
document.getElementById("myDiv").style.display = "";
return;
} else {
while (target.nodeName.toLowerCase() != "div" && target.nodeName.toLowerCase() != "html") {
target = target.parentNode;
}
if (target.nodeName.toLowerCase() == "html") {
document.getElementById("myDiv").style.display = "none";
}
}
})
</script>
</head>
<body>
<div id="myDiv" style="display:none;"><a href="http://www.jb51.net" target="_blank">脚本之家</a></div>
<input type="button" value="出来吧层" id="showDiv" />
</body>
</html>