使用原生js實現(xiàn)頁面蒙灰(mask)效果示例代碼

字號:


    像js的框架Extjs的mask()和unmask()功能提供了蒙灰效果,當(dāng)然jquery也提供了這種蒙灰方法,下面有個示例,大家可以參考下。
    對于web應(yīng)用開發(fā)者,當(dāng)用戶進(jìn)行界面瀏覽時如果后臺程序處理程序時間較長,那么用戶在網(wǎng)頁的等待時間會較長,但是如果頁面上沒有一個比較友好的提示方式
    (增加蒙灰效果),那么用戶體驗會不是特別良好,用戶不知道現(xiàn)在是不是應(yīng)該點擊別的程序,用戶并不知道是不是應(yīng)該繼續(xù)等待網(wǎng)頁,還是可以點擊別的頁面。
    現(xiàn)在就有一個比較良好的交互,就是增加蒙灰效果。像js的框架Extjs的mask()和unmask()功能提供了蒙灰效果,當(dāng)然jquery也提供了這種蒙灰方法。在此作者希望自己也能夠
    使用原生的js實現(xiàn)自己的蒙灰效果。故自己做了嘗試。實現(xiàn)了蒙灰效果。在此我只關(guān)注實現(xiàn),頁面美觀程度我沒有太多調(diào)整,所以頁面不太美觀。在此貼出實現(xiàn)代碼。
    在CODE上查看代碼片派生到我的代碼片
    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
    <HTML>
    <HEAD>
    <TITLE> New Document </TITLE>
    <META NAME="Generator" CONTENT="EditPlus">
    <META NAME="Author" CONTENT="">
    <META NAME="Keywords" CONTENT="">
    <META NAME="Description" CONTENT="">
    <style type="text/css">
    .maskStyle {
    background-color:#B8B8B8;
    z-index:1;
    filter:alpha(opacity=50);
    opacity:0.8;
    position:absolute;
    text-align:center;
    color:blue;
    font:bold 1em "宋體",Arial,Times;
    height:25px;
    font-weight:bold;
    overflow:hidden;
    }
    </style>
    </HEAD>
    <script type="text/javascript">
    function creatMaskLayer(effectItem,showText) {
    divItem = document.createElement("div");
    divItem.className="maskStyle";
    divItem.style.lineHeight=effectItem.offsetHeight+"px";
    divItem.innerText=showText;
    divItem.style.width=effectItem.offsetWidth;
    divItem.style.height=effectItem.offsetHeight;
    divItem.style.top=effectItem.offsetTop;
    divItem.style.left=effectItem.offsetLeft;
    return divItem;
    }
    function setMask() {
    var effectItem = document.getElementById("test");
    var existMaskItem = findMaskItem(effectItem);
    if(existMaskItem) {
    return;
    }
    var showText = "加載中...";
    effectItem.appendChild(creatMaskLayer(effectItem,showText));
    }
    function removeMask() {
    var effectItem = document.getElementById("test");
    var maskItem = findMaskItem(effectItem);
    if(maskItem) {
    effectItem.removeChild(maskItem);
    }
    }
    function findMaskItem(item) {
    var children = item.children;
    for(var i=0;i<children.length;i++) {
    if("maskStyle"==(children[i].className)) {
    return children[i];
    }
    }
    }
    </script>
    <BODY>
    <input type="button" value="蒙灰" onclick="setMask()"/>
    <input type="button" value="取消蒙灰" onclick="removeMask()"/>
    <br>
    <div id="test">
    蒙灰我吧
    <input type="button" value="測試是否還能點擊" onclick="alert('OK!')"/>
    </div>
    </BODY>
    </HTML>
    解釋一下代碼中比較重要的地方。
    .maskStyle是蒙灰層的樣式
    其中
    在CODE上查看代碼片派生到我的代碼片
    filter:alpha(opacity=50);
    opacity:0.8;
    是代表蒙灰層透明度,filter屬性是為了兼容IE8瀏覽器
    z-index 屬性設(shè)置元素的堆疊順序。擁有更高堆疊順序的元素總是會處于堆疊順序較低的元素的前面。
    PS:蒙灰效果需要把要蒙灰到element放到div中才可以