zl程序教程

您现在的位置是:首页 >  后端

当前栏目

使用原生js实现页面蒙灰(mask)效果示例代码

JS代码 实现 使用 示例 页面 效果 原生
2023-06-13 09:15:28 时间

对于web应用开发者,当用户进行界面浏览时如果后台程序处理程序时间较长,那么用户在网页的等待时间会较长,但是如果页面上没有一个比较友好的提示方式

(增加蒙灰效果),那么用户体验会不是特别良好,用户不知道现在是不是应该点击别的程序,用户并不知道是不是应该继续等待网页,还是可以点击别的页面。

现在就有一个比较良好的交互,就是增加蒙灰效果。像js的框架Extjs的mask()和unmask()功能提供了蒙灰效果,当然jquery也提供了这种蒙灰方法。在此作者希望自己也能够

使用原生的js实现自己的蒙灰效果。故自己做了尝试。实现了蒙灰效果。在此我只关注实现,页面美观程度我没有太多调整,所以页面不太美观。在此贴出实现代码。

在CODE上查看代码片派生到我的代码片

<!DOCTYPEHTMLPUBLIC"-//W3C//DTDHTML4.0Transitional//EN">
<HTML>
<HEAD>
<TITLE>NewDocument</TITLE>
<METANAME="Generator"CONTENT="EditPlus">
<METANAME="Author"CONTENT="">
<METANAME="Keywords"CONTENT="">
<METANAME="Description"CONTENT="">
<styletype="text/css">
.maskStyle{
background-color:#B8B8B8;
z-index:1;
filter:alpha(opacity=50);
opacity:0.8;
position:absolute;
text-align:center;
color:blue;
font:bold1em"宋体",Arial,Times;
height:25px;
font-weight:bold;
overflow:hidden;

}
</style>
</HEAD>
<scripttype="text/javascript">
functioncreatMaskLayer(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;
returndivItem;
}
functionsetMask(){
vareffectItem=document.getElementById("test");
varexistMaskItem=findMaskItem(effectItem);
if(existMaskItem){
return;
}
varshowText="加载中...";
effectItem.appendChild(creatMaskLayer(effectItem,showText));
}
functionremoveMask(){
vareffectItem=document.getElementById("test");
varmaskItem=findMaskItem(effectItem);
if(maskItem){
effectItem.removeChild(maskItem);
}
}
functionfindMaskItem(item){
varchildren=item.children;
for(vari=0;i<children.length;i++){
if("maskStyle"==(children[i].className)){
returnchildren[i];
}
}
}
</script>
<BODY>
<inputtype="button"value="蒙灰"onclick="setMask()"/>
<inputtype="button"value="取消蒙灰"onclick="removeMask()"/>
<br>
<divid="test"style="border:1pxsolid;width:300px;height:300px">
蒙灰我吧
<inputtype="button"value="测试是否还能点击"onclick="alert("OK!")"/>
</div>
</BODY>
</HTML>


解释一下代码中比较重要的地方。

.maskStyle是蒙灰层的样式

其中
在CODE上查看代码片派生到我的代码片

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

是代表蒙灰层透明度,filter属性是为了兼容IE8浏览器

z-index属性设置元素的堆叠顺序。拥有更高堆叠顺序的元素总是会处于堆叠顺序较低的元素的前面。

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