【前言】
本文分享个常见的特效,点击其他区域即元素外时隐藏元素。
【主体】
主要利用event事件对象(事件源)和冒泡实现
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>demo</title>
<style type="text/css">
*{
margin: 0;
padding: 0;
}
.area{
position: fixed;
display: none;
left: 50%;
top: 50%;
transform: translate(-50%,-50%);
background-color: rgba(0,0,0,0.3);
}
.closeBtn{
width: 30px;
height: 30px;
position: absolute;
right: 0;
top: 0;
border: none;
outline: none;
}
.closeBtn:hover{
background-color: rgba(255,0,0,0.3);
color: white;
cursor: pointer;
}
</style>
</head>
<body>
<form method="" action="">
<button type="button" class="login">登录</button>
</form>
<div class="area">
<button class="closeBtn">x</button>
</div>
<script type="text/javascript">
window.onload = function(){
function getByClass(classname){
return document.getElementsByClassName(classname);
}
var login = getByClass("login")[0];
var area = getByClass("area")[0];
var closeBtn = getByClass("closeBtn")[0];
// 显示
login.addEventListener("click",show,false);
function show(){
var client_width = document.body.clientWidth || document.documentElement.clientWidth;
var client_height = window.screen.height;
area.style.cssText = "display:block;width:"+client_width/2+"px;height:"+client_height/2+"px;"
}
// 关闭
closeBtn.addEventListener("click",close,false);
function close(){
area.style.cssText = "display:none";
}
// 点击其他位置关闭
document.onclick = function(event){
if(area.style.display == "block" && event.target.className != "login"){
if(event.target.className != area){
close();
}
}
}
//阻止冒泡
area.addEventListener("click",function(event){
var event = event || window.event;
var target = event.target || event.srcElement;
event.stopPropagation();
})
}
</script>
</body>
</html>
.