弹出框始终保持居中(包括有滚动条和窗体缩放时)
之前写的代码,都是在当前窗口位于居中,可是一旦窗口缩小或者放大都不是位于居中的位置了,但是一直想写的一个类似于alert弹出窗口的效果。
原理很简单:
获取当前屏幕(窗体)的宽度和高度,因为不同浏览器的窗体大小是不一样的。有了这个,可以计算出来横向居中和垂直居中的坐标。但是滑动了滚动条怎么依然横向居中和垂直居中呢?这个时候就要获取当前窗体距离页面顶部的高度和横向滚动条移动的宽度,加到刚刚的y轴坐标即可。
$(document)是获取整个网页的,$(window)是获取当前窗体的,这个要搞清楚。
最后把获取的坐标赋给窗体即可,窗体本身是绝对定位的,所以自然可以到窗体中间。
效果体验:http://runjs.cn/detail/tj4jq1qr
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>弹出确认框始终位于窗口正中央</title>
<style type="text/css">
.mask { position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: #000; opacity: 0.5; filter: alpha(opacity=50); display: none; z-index: 99; }
.alertBox {position: fixed; display: none; width: 250px; height: 100px; border: 1px solid #ccc; background: #ececec; text-align: center; z-index: 101; }
</style>
<script type="text/javascript" src="http://code.jquery.com/jquery.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('.btn').click(function() {
$('.mask').css({'display': 'block'});
center($('.alertBox'));
$('.alertBox').css({'display': 'block'});
$("body").css({"overflow":"hidden","height":"100%"});//隐藏滑动条
});
// 居中
function leftTop(obj){
var screenWidth = $(window).width();
var screenHeight = $(window).height();
var scrolltop = $(document).scrollTop();
var scrollleft = $(document).scrollLeft();
var objLeft = (screenWidth - obj.width())/2 + scrollleft ;
var objTop = (screenHeight - obj.height())/2 + scrolltop;
obj.css({left: objLeft + 'px', top: objTop + 'px'});
}
function center(obj) {
leftTop(obj);
//浏览器窗口大小改变时
$(window).resize(function() {
leftTop(obj);
});
//浏览器有滚动条时的操作、
$(window).scroll(function() {
leftTop(obj);
});
}
//确定取消的操作
$('.btn1,.btn2').click(function(){
$('.mask,.alertBox').hide();
$("body").css({"overflow":"auto"});
})
});
</script>
</head>
<body>
<input type="button" class="btn" value="btn" style="margin-top:2500px; margin-left:800px;"/>
<div style="height:3000px; width:3000px;">弹出确认框始终位于窗口的正中央</div>
<div class="mask"></div>
<div class="alertBox">
<p>确定要删除吗?</p>
<p><input type="button" value="确定" class="btn1"/>
<input type="button" value="取消"class="btn2"/></p>
</div>
</body>
</html>

浙公网安备 33010602011771号