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

jquery特效(7)—弹出遮罩层且内容居中

2015-12-13 18:27 801 查看
上周写了几个小特效,其中有个点击按钮弹出遮罩层的特效,下面来看最终实现的效果:



由于是测试的程序,所以我未加关闭的按钮。

一、主体程序

<!DOCTYPEhtml>
<html>
<head>
<metacharset="utf-8"/>
<title>弹出居中遮罩</title>
<metaname="viewport"content="width=device-width,initial-scale=1,minimum-scale=1,maximum-scale=1,user-scalable=no"/>
<linkrel="stylesheet"type="text/css"href="css/layout.css"/>
</head>
<body>
<sectionclass="test">
这里是主体内容<br/>
<inputtype="button"class="testButton"value="弹出遮罩"/>
</section>
<sectionclass="testBg"></section>
<sectionclass="testCont">
这里是弹出的内容测试
</section>
<scriptsrc="js/jquery-1.11.0.js"type="text/javascript"charset="utf-8"></script>
<scriptsrc="js/layout.js"type="text/javascript"charset="utf-8"></script>
</body>
</html>


二、CSS样式

*{
margin:0;
padding:0;
}
.testBg{
position:fixed;/*考虑主体内容可能过多出现竖直滚动条,建议用fixed*/
top:0;
background-color:#000;
filter:alpha(opacity=80);/*IE*/
-moz-opacity:0.8;/*Moz+FF*/
opacity:0.8;/*支持CSS3的浏览器(FF1.5也支持)*/
display:none;
}
.testCont{
position:fixed;/*考虑主体内容可能过多出现竖直滚动条,建议用fixed*/
top:0;
left:0;
width:200px;
border:1px#ffc700solid;
color:#ffc700;
display:none;
}




三、JS程序

这个才是本次随笔所说的重点,下面来看一段错误的JS程序:

$(function(){
$(".testBg").height($(window).height()).width($(window).width());//使遮罩的背景覆盖整个页面
vartestContTop=($(window).height()-$(".testCont").height())/2;//计算弹出的框距离页面顶部的距离
vartestContWidth=($(window).width()-$(".testCont").width())/2;//计算弹出的框距离页面左边的距离
$(".testCont").css({
"top":testContTop,
"left":testContWidth
});
$(".testButton").click(function(){
$(".testBg").show();

$(".testCont").show();

})})


上面这段程序看起来没有问题,那么来看一下输出的结果:



实际测量的时候上下的间距是不一致的,经过师父的指点才知道是浏览器渲染的结果,具体的原理请看这篇文章:http://www.cnblogs.com/lhb25/p/how-browsers-work.html

那么正确的JS程序是:

$(function(){
$(".testBg").height($(window).height()).width($(window).width());//使遮罩的背景覆盖整个页面

$(".testButton").click(function(){
$(".testBg").show();
$(".testCont").show();
showDiv();
})
})
functionshowDiv(){

vartestContTop=($(window).height()-$(".testCont").height())/2;//计算弹出的框距离页面顶部的距离
vartestContWidth=($(window).width()-$(".testCont").width())/2;//计算弹出的框距离页面左边的距离
$(".testCont").css({
"top":testContTop,
"left":testContWidth
});
}


从上面程序可以看出在遮罩层弹出显示以后再执行一个函数动态的设置弹出层的背景大小和距离页面的上间距和左间距,而不是一开始加载JS时就已经设置好弹出层各项参数。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: