原生JavaScript实现页面蒙灰效果

作者:闭包旅人

时间:2026-10-28

浏览:611

本文介绍如何使用原生JavaScript实现页面蒙灰效果,以优化后台处理时的用户等待体验。通过创建透明遮罩层并设置z-index和透明度属性,有效防止用户在加载期间误操作,提供类似ExtJS和jQuery的mask功能。

文章目录

原生JavaScript实现页面蒙灰效果

对于Web应用开发者而言,当后台程序处理时间较长导致用户等待时,若页面缺乏友好的提示方式,

用户体验往往不佳。用户无法判断是否应点击其他程序,也不清楚是继续等待还是可以访问其他页面。

此时,增加蒙灰效果是一种良好的交互解决方案。例如,ExtJS框架提供了mask()和unmask()功能,jQuery也具备类似的蒙灰方法。

作者尝试使用原生JavaScript实现自定义的蒙灰效果,并成功实现了该功能。虽然页面美观度未做过多调整,但核心功能已实现,以下贴出相关代码。

在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定义了蒙灰层的样式。

其中,


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

opacity属性用于设置蒙灰层的透明度,而filter属性则是为了兼容IE8浏览器。

z-index属性用于设置元素的堆叠顺序,拥有更高堆叠顺序的元素会始终显示在堆叠顺序较低的元素前方。

注意:实现蒙灰效果时,需要将目标元素包裹在div中才能生效。

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章