之前寫的代碼,都是在當前窗口位於居中,可是一旦窗口縮小或者放大都不是位於居中的位置了,但是一直想寫的一個類似於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>