html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<style>
#div {
background: red;
100px;
height: 100px;
display: none;
}
</style>
<script type="text/javascript" src="js/jquery-3.0.0.min.js"></script>
<script type="text/javascript">
$(function () {
var oDiv = $("#div")[0];
var oBtn = $("#btn")[0];
document.onclick = function (ev) {
var e = ev || event;
var target = e.target || e.srcElement;
if (e.target.id != 'div') //事件对象
{
oDiv.style.display = "none";
}
}
oBtn.onclick = function (ev) {
var e = ev || event;
oDiv.style.display = "block";
if (e && e.stopPropagation) { //阻止冒泡
e.stopPropagation();
} else {
window.event.cancelBubble = true;
}
}
});
</script>
</head>
<body>
<div id="div"></div>
<input type="button" value='点击' id="btn"/>
</body>
</html>
result:
方法二:
html:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>
<style type="text/css">
.popup {
background-color: #33CC99;
display: none;
200px;
height: 200px;
/*position: absolute; left: 400px; top: 100px;*/
border: 5px solid #FF9999;
border-radius: 5px;
margin: 0 auto;
margin-top: 100px;
}
.popup ul li {
line-height: 1.5em;
}
</style>
<script type="text/javascript" src="js/jquery-3.0.0.min.js"></script>
<script type="text/javascript">
</script>
</head>
<body>
<div class="container">
<p>
<button id="btnPop" type="button">弹出div层</button>
</p>
<div id="popup" class="popup">
<ul>
<li><span>css</span></li>
<li><span>html</span></li>
<li><span>js</span></li>
<li><span>csharp</span></li>
<li><span>sql</span></li>
</ul>
</div>
</div>
<script type="text/javascript">
$(function () {
var oBtn = $("#btnPop")[0];
oBtn.onclick = showPopup;
function showPopup() {
document.getElementById("popup").style.display = "block";
}
function hidePopup() {
document.getElementById("popup").style.display = "none";
}
document.getElementById("popup").onclick = function (e) {
e = e || window.event;
if (window.event) {
e.cancelBubble = true;
} else {
e.stopPropagation();
}
};
document.body.onclick = function (e) {
e = e || window.event;
var target = e.target || e.srcElement;
if (target.id === "btnPop") return;
hidePopup();
};
})
</script>
</body>
</html>