原理很简单: 获取当前屏幕(窗体)的宽度和高度,因为不同浏览器的窗体大小是不一样的。有了这个,可以计算出来垂直居中的坐标。但是滑动了滚动条怎么依然垂直居中呢?这个时候就要获取当前窗体距离页面顶部的高度,加到刚刚的y轴坐标即可。 $(document)是获取整个网页的,$(window)是获取当前窗体的,这个要搞清楚。 最后把获取的坐标赋给窗体即可,窗体本身是绝对定位的,所以自然可以到窗体中间。 具体代码: 复制代码 代码如下: 弹出确认框始终位于窗口的中间位置的测试 <BR>.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; } <BR>.mess { position: absolute; display: none; width: 250px; height: 100px; border: 1px solid #ccc; background: #ececec; text-align: center; z-index: 101; } <BR> <BR>$(document).ready(function() { <BR>$('.btn').click(function() { <BR>$('.mask').css({'display': 'block'}); <BR>center($('.mess')); <BR>check($(this).parent(), $('.btn1'), $('.btn2')); <BR>}); <BR>// 居中 <BR>function center(obj) { <BR>var screenWidth = $(window).width(), screenHeight = $(window).height(); //当前浏览器窗口的 宽高 <BR>var scrolltop = $(document).scrollTop();(),//获取当前窗口距离页面顶部高度 <BR>var objLeft = (screenWidth - obj.width())/2 ; <BR>var objTop = (screenHeight - obj.height())/2 + scrolltop; <BR>obj.css({left: objLeft + 'px', top: objTop + 'px','display': 'block'}); <BR>//浏览器窗口大小改变时 <BR>$(window).resize(function() { <BR>screenWidth = $(window).width(); <BR>screenHeight = $(window).height(); <BR>scrolltop = $(document).scrollTop(); <BR>objLeft = (screenWidth - obj.width())/2 ; <BR>objTop = (screenHeight - obj.height())/2 + scrolltop; <BR>obj.css({left: objLeft + 'px', top: objTop + 'px','display': 'block'}); <BR>}); <BR>//浏览器有滚动条时的操作、 <BR>$(window).scroll(function() { <BR>screenWidth = $(window).width(); <BR>screenHeight = $(widow).height(); <BR>scrolltop = $(document).scrollTop(); <BR>objLeft = (screenWidth - obj.width())/2 ; <BR>objTop = (screenHeight - obj.height())/2 + scrolltop; <BR>obj.css({left: objLeft + 'px', top: objTop + 'px','display': 'block'}); <BR>}); <BR>} <BR>//确定取消的操作 <BR>function check(obj, obj1, obj2) { <BR>obj1.click(function() { <BR>obj.remove(); <BR>closed($('.mask'), $('.mess')); <BR>}); <BR>obj2.click(function() { <BR>closed($('.mask'), $('.mess')); <BR>}) ; <BR>} <BR>// 隐藏 的操作 <BR>function closed(obj1, obj2) { <BR>obj1.hide(); <BR>obj2.hide(); <BR>} <BR>}); <BR> 弹出确认框始终位于窗口的中间位置的测试 确定要删除吗?