代碼如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
<style>
#mask {
width:100%;
height:100%;
background-color:#000;
position:absolute;
top:0;
left:0;
z-index:2;
opacity:0.3;
/*兼容IE8及以下版本瀏覽器*/
filter: alpha(opacity=30);
display:none;
}
#dialog {
width:200px;
height:200px;
background-color:white;
margin: auto;
position: absolute;
z-index:3;
top: 0;
bottom: 0;
left: 0;
right: 0;
display:none;
}
</style>
</head>
<body>
<div id="mask"></div>
<div id="dialog">
<a href="javascript:hideDialog()">關(guān)閉</a>
</div>
<button id='popMaskBtn'>彈出遮罩層</button>
</body>
<script>
//遮罩層
var mask = document.getElementById("mask");
//彈框
var dialog = document.getElementById("dialog");
//窗口加載完成事件
window.onload = function(){
//為彈出遮罩層的按鈕添加事件
document.getElementById("popMaskBtn").addEventListener('click',function(){
mask.style.display = "block";
dialog.style.display = "block";
});
//添加點(diǎn)擊事件-點(diǎn)擊遮罩層后關(guān)閉遮罩層
window.addEventListener("click",function(event){
if(event.target == mask){
hideDialog();
}
});
};
//關(guān)閉遮罩層
function hideDialog(){
mask.style.display = "none";
dialog.style.display = "none";
}
</script>
</html>
實(shí)現(xiàn)效果:
點(diǎn)擊按鈕,顯示遮罩層,彈出彈框
點(diǎn)擊遮罩層,隱藏遮罩層,隱藏彈框