需要冒泡添加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>