本文为大家分享了jQuery点击按钮弹出遮罩层且内容居中的特效,下面来看最终实现的效果:
由于是测试的程序,所以我未加关闭的按钮。
一、主体程序
弹出居中遮罩这里是主体内容
这里是弹出的内容测试
二、CSS样式
*{
margin: 0;
padding: 0;
}
.testBg{
position: absolute;
top: 0;
background-color: #000;
filter:alpha(opacity=80); /* IE */
-moz-opacity:0.8; /* Moz + FF */
opacity: 0.8; /* 支持CSS3的浏览器(FF 1.5也支持)*/
display:none ;
}
.testBg .testCont{
position: absolute;
top: 0;
left: 0;
width:200px;
border: 1px #ffc700 solid;
color: #ffc700;
}
三、JS程序这个才是本次随笔所说的重点,下面来看一段错误的JS程序:
$(function(){
$(".testBg").height($(window).height()).width($(window).width()); //使遮罩的背景覆盖整个页面
var testContTop=($(window).height()-$(".testCont").height())/2; //计算弹出的框距离页面顶部的距离
var testContWidth=($(window).width()-$(".testCont").width())/2; //计算弹出的框距离页面左边的距离
$(".testCont").css({
"top":testContTop,
"left":testContWidth
});
$(".testButton").click(function(){
$(".testBg").show();
})
})
上面这段程序看起来没有问题,那么来看一下输出的结果:
实际测量的时候上下的间距是不一致的。
那么正确的JS程序是:
$(function(){
$(".testBg").height($(window).height()).width($(window).width());//使遮罩的背景覆盖整个页面
$(".testButton").click(function(){
$(".testBg").show();
showDiv();
})
})
function showDiv(){
var testContTop=($(window).height()-$(".testCont").height())/2; //计算弹出的框距离页面顶部的距离
var testContWidth=($(window).width()-$(".testCont").width())/2; //计算弹出的框距离页面左边的距离
$(".testCont").css({
"top":testContTop,
"left":testContWidth
});
}
从上面程序可以看出在遮罩层弹出显示以后再执行一个函数动态的设置弹出层的背景大小和距离页面的上间距和左间距,而不是一开始加载JS时就已经设置好弹出层各项参数。
以上就是本文的全部内容,教大家如何实现点击按钮弹出遮罩层且内容居中的效果,