描述:当用户点击登录的时候,弹出一片区域,中间空白区域与其他区域不同,其他区域为半透明状态。点击透明状态的时候,弹出区域关闭,点击中间区域,无效。
技术难点:取消冒泡
实现代码:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>隐藏模态框</title>
<style>
body,html {
height: 100%;
padding: 0;
margin: 0;
}
.mask {
width: 100%;
height: 100%;
position: fixed;
top: 0;
left: 0;
display: none;
background: rgba(0, 0, 0, 0.6);
}
.login {
width: 400px;
height: 300px;
cursor: pointer;
background-color: #fff;
margin: 200px auto;
}
</style>
</head>
<body>
<div class="mask">
<div class="login" id="login"></div>
</div>
<a href="#">注册</a>
<a href="#">登陆</a>
</body>
</html>
<script>
//模态框
var mask = document.getElementsByClassName("mask")[0];
//点击a链接
var a = document.getElementsByTagName("a")[1];
//a的点击事件,点击之后弹出模态框
a.onclick = function (event) {
event = event || window.event;
mask.style.display = "block";
//取消冒泡
if(event || event.stopPropagation){
event.stopPropagation();
}else {
event.cancelBubble = true;
}
}
document.onclick = function (event) {
event = event || window.event;
//获取点击的区域
var box = event.target?event.target:event.srcElement;
if(box.id !== "login"){
mask.style.display = "none";
}
}
</script>