您的位置:首页 > Web前端 > JavaScript

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

2014-06-20 11:37 1471 查看

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

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

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

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

在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上查看代码片派生到我的代码片

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

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

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

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

内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  原生js 蒙灰
相关文章推荐