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>

关注我

我的微信公众号:前端开发博客,在后台回复以下关键字可以获取资源。

  • 回复「小抄」,领取Vue、JavaScript 和 WebComponent 小抄 PDF
  • 回复「Vue脑图」获取 Vue 相关脑图
  • 回复「思维图」获取 JavaScript 相关思维图
  • 回复「简历」获取简历制作建议
  • 回复「简历模板」获取精选的简历模板
  • 回复「加群」进入500人前端精英群
  • 回复「电子书」下载我整理的大量前端资源,含面试、Vue实战项目、CSS和JavaScript电子书等。
  • 回复「知识点」下载高清JavaScript知识点图谱

每日分享有用的前端开发知识,加我微信:caibaojian89 交流