要讓彈跳視窗像 alert 那樣永遠停在畫面正中央,關鍵在兩個座標計算。
第一步:取得當前視窗的寬與高。不同瀏覽器、不同視窗尺寸的可用區域都不一樣,所以必須用 $(window).width() 與 $(window).height() 動態讀取,有了這組數字才能算出水平與垂直的置中座標。
第二步:加上頁面已經捲動的距離。如果只算視窗置中,使用者捲到頁面中段時彈出框就會跑到畫面外——因為它用的是絕對定位,參照的是文件而非視窗。把 $(document).scrollTop() 加到 Y 座標上,視覺上就仍然居中。
順帶釐清一個常見混淆:$(document) 指的是整個網頁文件,$(window) 指的是目前的瀏覽器視窗,兩者取值含義完全不同。
最後把算好的座標寫給那個 position:absolute 的容器即可。另外記得掛上 resize 與 scroll 兩個事件,視窗一改大小或使用者一捲動就重算,這樣才不會跑位。
<!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); /* 兼容舊 IE */
display: none; z-index: 99;
}
.mess {
position: absolute; display: none;
width: 250px; height: 100px;
border: 1px solid #ccc; background: #ececec;
text-align: center; z-index: 101;
}
</style>
<script type="text/javascript" src="jquery-1.6.1.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$('.btn').click(function () {
$('.mask').css({ 'display': 'block' });
center($('.mess'));
check($(this).parent(), $('.btn1'), $('.btn2'));
});
// 計算並套用置中座標
function center(obj) {
var screenWidth = $(window).width(),
screenHeight = $(window).height(),
scrolltop = $(document).scrollTop();
var objLeft = (screenWidth - obj.width()) / 2;
var objTop = (screenHeight - obj.height()) / 2 + scrolltop;
obj.css({ left: objLeft + 'px', top: objTop + 'px', 'display': 'block' });
// 視窗尺寸改變時重算
$(window).resize(function () {
screenWidth = $(window).width();
screenHeight = $(window).height();
scrolltop = $(document).scrollTop();
objLeft = (screenWidth - obj.width()) / 2;
objTop = (screenHeight - obj.height()) / 2 + scrolltop;
obj.css({ left: objLeft + 'px', top: objTop + 'px', 'display': 'block' });
});
// 出現捲動條時重算
$(window).scroll(function () {
screenWidth = $(window).width();
screenHeight = $(window).height();
scrolltop = $(document).scrollTop();
objLeft = (screenWidth - obj.width()) / 2;
objTop = (screenHeight - obj.height()) / 2 + scrolltop;
obj.css({ left: objLeft + 'px', top: objTop + 'px', 'display': 'block' });
});
}
// 確定 / 取消
function check(obj, obj1, obj2) {
obj1.click(function () {
obj.remove();
closed($('.mask'), $('.mess'));
});
obj2.click(function () {
closed($('.mask'), $('.mess'));
});
}
function closed(obj1, obj2) {
obj1.hide();
obj2.hide();
}
});
</script>
</head>
<body>
<input type="button" class="btn" value="btn" />
<div>彈出確認框始終位於窗口中間位置的測試</div>
<div class="mask"></div>
<div class="mess">
<p>確定要刪除嗎?</p>
<p>
<input type="button" value="確定" class="btn1" />
<input type="button" value="取消" class="btn2" />
</p>
</div>
</body>
</html>
這份寫法把置中計算在 resize 與 scroll 裡重複了兩遍,實務上可以抽成一個獨立函式,讓三處共用;另外固定定位的遮罩若改用 position:fixed 搭配 top:50%;margin-top 負值,在支援的瀏覽器上能省掉 scroll 監聽。不過作為理解座標計算的入門範例,把每一步攤開來寫反而更清楚。