jQuery点击区域外消失

需要冒泡添加e.stopPropagation


<!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=utf-8" />
<title>box - mming</title>
<meta name="keywords" content="" />
<meta name="description" content="" />

<style type="text/css">
.box {width:100px; height:100px; background:#f00;}
</style>

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
<script type="text/javascript">
$(function() {
$(document).click(function() {
$('.box').hide();
})
$('.box').click(function(event) {
event.stopPropagation();
})
});
</script>
</head>

<body>

<div>box</div>

</body>
</html>

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>点击一个连接显示层</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;">就等你包养了</div>
<input type="button" value="快来摸我" id="showDiv" />
</body>
</html>

「五年博客,如果觉得我的文章对您有用,请帮助本站成长」

订阅周报 关注微博

原创文章:jQuery点击区域外消失 ,未经许可,禁止转载,©版权所有
原文出处:前端开发博客 (http://caibaojian.com/1087.html)

发表评论

请登录后发表评论:

“jQuery点击区域外消失”有1个评论

  1. 淡眉小牛

    while (target.nodeName.toLowerCase() != "div" && target.nodeName.toLowerCase() != "html") {
    target = target.parentNode;
    }
    这个有什么作用呢?

    登录回复