彈窗遮罩層原理及實現
一、說明:
我們知道,如果在網頁中需要載入一個彈窗時同常是不希望點選到彈窗以外的區域從而導致錯誤操作的。這個時候呢我們就可以使用遮罩層來實現彈窗外部區域遮蔽的功能。
二、原理:
在彈窗和頁面之間建立一個div並使之鋪滿整個螢幕,同時讓這個div半透明。這樣我們就可以即能看到頁面的內容,又無法點選到彈窗外的內容了。
三、用到的技術:
js控制display的屬性值以及設定遮罩層opacity的值為0.3 (小於1就行)
四、範例:
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>遮罩層</title>
<style>
html,body {
margin:0;
height:100%;
}
#test {
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;
}
#log_window {
width:200px;
height:200px;
background-color:red;
margin: auto;
position: absolute;
z-index:3;
top: 0;
bottom: 0;
left: 0;
right: 0;
display:none;
}
</style>
<script>
function shield(){
var s = document.getElementById("test");
s.style.display = "block";
var l = document.getElementById("log_window");
l.style.display = "block";
}
function cancel_shield(){
var s = document.getElementById("test");
s.style.display = "none";
var l = document.getElementById("log_window");
l.style.display = "none";
}
</script>
</head>
<body>
<a href="javascript:shield()">開啟遮罩</a>
<div id="test"></div>
<div id="log_window">
<a href="javascript:cancel_shield()">關閉</a>
</div>
</body>
</html>