遮罩层的作用:
1.首先我们要明白,遮罩层的作用就是将指定区域覆盖,使其失去原有的功能(如: 点击事件,移入移出效果)。
遮罩层的原理
在指定区域加上一个半透明的蒙版,也可以再在蒙版上面再加一个你想要实现的效果。一般通过定位(position) ,使用层级(z-index)来实现遮罩层的效果。
遮罩层相关代码演示
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
html,body{
width: 100%;
height: 100%;
}
.div1{
width: 200px;
height: 200px;
background-color: antiquewhite;
}
.div2{
width: 200px;
height: 200px;
background-color: aqua;
}
.mask{
width: 100%;
height: 100%;
background-color: black;
position: absolute;
opacity: 0.3;
left: 0;
top: 0;
z-index: 1;
display: none;
}
button{
width: 300px;
height: 100px;
font-size: 20px;
line-height: 100px;
text-align: center ;
}
.close{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%,-50%);
display: none;
z-index:10;
}
</style>
</head>
<body>
<button class="open">点击启用遮罩层</button>
<button class="close">点击关闭遮罩层</button>
<div class="div1"></div>
<div class="div2"></div>
</body>
<div class="mask"></div>
<script>
var div1=document.getElementsByClassName("div1")[0]
var div2=document.querySelector(".div2");
div1.addEventListener("mouseover",function(){this.style.backgroundColor='red'})
div1.addEventListener("mouseout",function(){this.style.backgroundColor='antiquewhite'})
div2.addEventListener("mouseover",function(){this.style.backgroundColor='blue'})
div2.addEventListener("mouseout",function(){this.style.backgroundColor='aqua'})
//遮罩层mask
var mask=document.querySelector(".mask");
var open=document.querySelector(".open")
var close=document.querySelector(".close")
open.onclick=function(){
mask.style.display='block'
close.style.display="block"
}
close.onclick=function(){
mask.style.display='none'
close.style.display='none'
}
</script>
</html>
分析:
1.在不启用遮罩层的情况下,下面的两个方块可以通过触发事件来实现移入移出来改变颜色
2.启用遮罩层后,这两个方块的事件将不会再被触发,因为遮罩层(mask)在上方将其覆盖(之所以看得见,是因为将透明度opacity设为原来的30%)
3.遮罩层上方的按钮之所以没有被覆盖,是因为通过定位,将层级(z-index)提升到比遮罩层高,所以遮罩层无法将其覆盖,原有的功能(点击事件)依然能够触发。
效果演示
觉得对你有帮助,点个赞再走吧!