很多时候我们想去某某网站干点什么的时候,就会让我们先注册登录后才可以访问内容,而现在很多网站注册登录的时候都会有一种遮罩层的效果,就是背景是带有透明度的黑色遮罩,盖满整个网站,然后登录框弹出固定在屏幕的居中位置。那么,今天就练练这个实用而简单的效果吧。PS:这个是我学习后练习的demo!
首先,需要有一个按钮来模拟登录:登录
然后呢,我们想通过点击这个按钮实现这样一个效果:
从上面这张图片,我们可以看到,灰色背景就是遮罩层,而浅蓝色的区域就是登陆框位置所在了。OK,下面先看一下HTML结构和css样式:
我是登录框哟!
这里只是将HTML结构拿出来讲一下,但是下面我们是通过JS来创建它们的,所以这里只是为了方便我们理解,并不需要放在html文件里。
CSS样式:#close{
background:url(img/close.png) no-repeat;
width:30px;
height:30px;
cursor:pointer;
position:absolute;
right:5px;
top:5px;
text-indent:-999em;
}
#mask{
background-color:#ccc;
opacity:0.7;
filter: alpha(opacity=70);
position:absolute;
left:0;
top:0;
z-index:1000;
}
#login{
position:fixed;
z-index:1001;
}
.loginCon{
position:relative;
width:670px;
height:380px;
background:lightblue;
border:3px solid #333;
text-align: center;
}
css样式中需要注意一下z-index属性,因为我们需要让遮罩层盖住除了登录框之外所有的页面内容,所以,需要确保登录框的层次最高,遮罩层次之,所以一般将这两个的z-index属性值设置为比较高的数值,但遮罩层要比登陆框少一层。然后还有一点就是遮罩层必须设置透明度,不然就太难看了,用户体验极其不好!
JS实现代码:function dialog(){
//获取页面的高度和宽度
var sWidth=document.body.scrollWidth || document.documentElement.scrollWidth;
var sHeight=document.body.scrollHeight || document.documentElement.scrollHeight;
//获取页面的可视区域高度和宽度
var wHeight=document.documentElement.clientHeight || document.body.clientHeight;
//创建遮罩层
var oMask=document.createElement("div");
oMask.id="mask";
oMask.style.height=sHeight+"px";
oMask.style.width=sWidth+"px";
document.body.appendChild(oMask); //添加到body末尾
//创建登录框
var oLogin=document.createElement("div");
oLogin.id="login";
oLogin.innerHTML="
document.body.appendChild(oLogin);
//获取登陆框的宽和高
var dHeight=oLogin.offsetHeight;
var dWidth=oLogin.offsetWidth;
//设置登陆框的left和top
oLogin.style.left=sWidth/2-dWidth/2+"px";
oLogin.style.top=wHeight/2-dHeight/2+"px";
//获取关闭按钮
var oClose=document.getElementById("close");
//点击关闭按钮和点击登陆框以外的区域都可以关闭登陆框
oClose.οnclick=oMask.οnclick=function(){
document.body.removeChild(oLogin);
document.body.removeChild(oMask);
};
}
window.οnlοad=function(){
var oBtn=document.getElementById("btnLogin");
//点击登录按钮
oBtn.οnclick=function(){
dialog();
}
}
这种方法是通过JS在事件绑定里动态创建和移除这些标签,然后设置他们的 id 和 style 属性。当然,我们也可以将HTML结构先放在html文件里,默认情况下隐藏它们,然后在事件绑定里控制它们的显示与隐藏即可!
更多弹出层特效代码,请访问:js代码特效 栏目