之前写的代码,都是在当前窗口位于居中,可是一旦窗口缩小或者放大都不是位于居中的位置了,但是一直想写的一个类似于alert弹出窗口的效果。
原理很简单:
获取当前屏幕(窗体)的宽度和高度,因为不同浏览器的窗体大小是不一样的。有了这个,可以计算出来垂直居中的坐标。但是滑动了滚动条怎么依然垂直居中呢?这个时候就要获取当前窗体距离页面顶部的高度,加到刚刚的y轴坐标即可。
$(document)是获取整个网页的,$(window)是获取当前窗体的,这个要搞清楚。
最后把获取的坐标赋给窗体即可,窗体本身是绝对定位的,所以自然可以到窗体中间。
具体代码:
1 <!DOCTYPE HTML> 2 <html> 3 <head> 4 <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 5 <title>弹出确认框始终位于窗口的中间位置的测试</title> 6 <style type="text/css"> 7 8 .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; } 9 .mess { position: absolute; display: none; width: 250px; height: 100px; border: 1px solid #ccc; background: #ececec; text-align: center; z-index: 101; } 10 </style> 11 <script type="text/javascript" src="jquery-1.6.1.min.js"></script> 12 <script type="text/javascript"> 13 $(document).ready(function() { 14 $('.btn').click(function() { 15 $('.mask').css({'display': 'block'}); 16 center($('.mess')); 17 check($(this).parent(), $('.btn1'), $('.btn2')); 18 }); 19 // 居中 20 function center(obj) { 21 22 var screenWidth = $(window).width(), screenHeight = $(window).height(); //当前浏览器窗口的 宽高 23 var scrolltop = $(document).scrollTop();//获取当前窗口距离页面顶部高度 24 25 var objLeft = (screenWidth - obj.width())/2 ; 26 var objTop = (screenHeight - obj.height())/2 + scrolltop; 27 28 obj.css({left: objLeft + 'px', top: objTop + 'px','display': 'block'}); 29 //浏览器窗口大小改变时 30 $(window).resize(function() { 31 screenWidth = $(window).width(); 32 screenHeight = $(window).height(); 33 scrolltop = $(document).scrollTop(); 34 35 objLeft = (screenWidth - obj.width())/2 ; 36 objTop = (screenHeight - obj.height())/2 + scrolltop; 37 38 obj.css({left: objLeft + 'px', top: objTop + 'px','display': 'block'}); 39 40 }); 41 //浏览器有滚动条时的操作、 42 $(window).scroll(function() { 43 screenWidth = $(window).width(); 44 screenHeight = $(widow).height(); 45 scrolltop = $(document).scrollTop(); 46 47 objLeft = (screenWidth - obj.width())/2 ; 48 objTop = (screenHeight - obj.height())/2 + scrolltop; 49 50 obj.css({left: objLeft + 'px', top: objTop + 'px','display': 'block'}); 51 }); 52 53 } 54 //确定取消的操作 55 function check(obj, obj1, obj2) { 56 obj1.click(function() { 57 obj.remove(); 58 closed($('.mask'), $('.mess')); 59 }); 60 obj2.click(function() { 61 closed($('.mask'), $('.mess')); 62 }) ; 63 } 64 // 隐藏 的操作 65 function closed(obj1, obj2) { 66 obj1.hide(); 67 obj2.hide(); 68 } 69 70 }); 71 </script> 72 </head> 73 <body> 74 <input type="button" class="btn" value="btn"/> 75 <div>弹出确认框始终位于窗口的中间位置的测试</div> 76 <div class="mask"></div> 77 <div class="mess"> 78 <p>确定要删除吗?</p> 79 <p><input type="button" value="确定" class="btn1"/> 80 <input type="button" value="取消"class="btn2"/></p> 81 </div> 82 </body> 83 </html>
转载自:http://www.cnblogs.com/web-ed2/archive/2011/09/28/2194861.html