使用原生js實現頁面蒙灰(mask)效果範例程式碼

來源:互聯網
上載者:User

對於web應用開發人員,當使用者進行介面瀏覽時如果背景程式處理常式時間較長,那麼使用者在網頁的等待時間會較長,但是如果頁面上沒有一個比較友好的提示方式

(增加蒙灰效果),那麼使用者體驗會不是特別良好,使用者不知道現在是不是應該點擊別的程式,使用者並不知道是不是應該繼續等待網頁,還是可以點擊別的頁面。

現在就有一個比較良好的互動,就是增加蒙灰效果。像js的架構Extjs的mask()和unmask()功能提供了蒙灰效果,當然jquery也提供了這種蒙灰方法。在此作者希望自己也能夠

使用原生的js實現自己的蒙灰效果。故自己做了嘗試。實現了蒙灰效果。在此我只關注實現,頁面美觀程度我沒有太多調整,所以頁面不太美觀。在此貼出實現代碼。

在CODE上查看代碼片派生到My 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" style="border:1px solid;width:300px;height:300px"> 蒙灰我吧 <input type="button" value="測試是否還能點擊" onclick="alert('OK!')"/> </div> </BODY> </HTML>


解釋一下代碼中比較重要的地方。

.maskStyle是蒙灰層的樣式

其中
在CODE上查看代碼片派生到My Code片

filter:alpha(opacity=50); opacity:0.8; 

是代表蒙灰層透明度,filter屬性是為了相容IE8瀏覽器

z-index 屬性設定元素的堆疊順序。擁有更高堆疊順序的元素總是會處於堆疊順序較低的元素的前面。

PS:蒙灰效果需要把要蒙灰到element放到div中才可以

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.