遮罩层的简单使用分析
今天我们来聊聊遮罩层的简单使用。遮罩层是基于以下几个属性来实现的:
1.z-index
定义:z-index 属性设置元素的堆叠顺序。拥有更高堆叠顺序的元素总是会处于堆叠顺序较低的元素的前面。
简单来说就是谁的z-index属性值高在z轴方向会在更外面。
2.opacity
作用:规定不透明度。从 0.0 (完全透明)到 1.0(完全不透明)。
3.display
这里我们只需要理解这个属性的两个值:
none :此元素不会被显示。
block :此元素将显示为块级元素,此元素前后会带有换行符。(简单理解就是显示)
4.position
定位,需要这个属性是因为,有了这个属性才可以控制遮罩层放哪(一般在中心位置)。
这些了解以后,看看下面的案例:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>遮罩层</title>
<style>
html,body {
margin:0;
height:100%;
}
#shade{
position:absolute;
top:0;
left:0;
z-index:2;
/*z-index 属性设置元素的堆叠顺序。拥有更高堆叠顺序的元素总是会处于堆叠顺序较低的元素的前面。*/
width:100%;
height:100%;
background-color:#000;
opacity:0.3;
/*opacity透明度*/
/*兼容IE8及以下版本浏览器*/
filter: alpha(opacity=30);
display:none;
}
#modal {
position: absolute;
z-index:3;
top: 0;
bottom: 0;
left: 0;
right: 0;
width:200px;
height:200px;
margin: auto;
display:none;
background-color:skyblue;
}
</style>
<script>
window.onload=function(){
var a1=document.getElementById('a1');
var a2=document.getElementById('a2');
a1.onclick=shield;
a2.onclick=cancel_shield;
function shield(e){
e.preventDefault();//取消事件的默认动作。
var shade = document.getElementById("shade");
shade.style.display = "block";
var modal = document.getElementById("modal");
modal.style.display = "block";
}
function cancel_shield(e){
e.preventDefault();//取消事件的默认动作。
var shade = document.getElementById("shade");
shade.style.display = "none";
var modal = document.getElementById("modal");
modal.style.display = "none";
}
};
</script>
</head>
<body>
<a id="a1" href="#">打开遮罩</a>
<div id="shade"></div>
<div id="modal">
<a id="a2" href="#">关闭</a>
</div>
</body>
</html>
效果图:
开始:点击:打开遮罩
总结
总的来说,遮罩其实是在原来界面上加上一个半透明的蒙版,然后在外面在加一个你想要实现的效果。注意点:1.z-index的值是大的在外面。2.position属性如果不设置则无法移动位置。