彈出層居中聽起來簡單,實際上有一個常被忽略的細節:頁面滾動之後,「居中」是相對於視窗還是相對於文檔?用戶看到的居中,顯然是前者。而絕大多數新手寫的版本,滾動一下就會偏掉。
showDiv($("#pop"));
function showDiv(obj) {
$(obj).show();
center(obj);
$(window).scroll(function () { center(obj); });
$(window).resize(function () { center(obj); });
}
function center(obj) {
var windowWidth = document.documentElement.clientWidth;
var windowHeight = document.documentElement.clientHeight;
var popupHeight = $(obj).height();
var popupWidth = $(obj).width();
$(obj).css({
"position": "absolute",
"top": (windowHeight - popupHeight) / 2 + $(document).scrollTop(),
"left": (windowWidth - popupWidth) / 2
});
}
這個版本的思路是對的:用 position: absolute 配合 scrollTop() 補償,讓彈層始終停在視窗中央。同時監聽 scroll 和 resize 兩個事件,滾動或改變窗口大小時重新計算。
如果用 position: fixed,元素本身就釘在視井上,不需要補 scrollTop,也不需要監聽 scroll 事件:
function centerFixed(obj) {
var $obj = $(obj);
$obj.css({
"position": "fixed",
"top": ( $(window).height() - $obj.outerHeight() ) / 2,
"left": ( $(window).width() - $obj.outerWidth() ) / 2
});
}
// 只需在窗口尺寸變化時重新計算
$(window).resize(function () { centerFixed($("#pop")); });
兩種方案各有適用場景:absolute 兼容更老的 IE,fixed 代碼更少、性能更好(少了一個 scroll 監聽)。現代項目直接用 fixed。
這是一個容易出錯的地方。height() 只返回內容高度,不包含 padding 和 border;outerHeight() 包含 padding 和 border,outerHeight(true) 連 margin 也算進去。彈層幾乎一定有 padding 和邊框,用 height() 計算出來的居中會偏下偏右幾個像素——正是那種「看著不對但說不出哪不對」的偏差。
其實現在完全不需要 JavaScript。Flexbox 三行就能搞定:
.overlay {
position: fixed;
inset: 0; /* 等於 top/right/bottom/left 全為 0 */
background: rgba(0,0,0,.5);
display: flex;
align-items: center; /* 垂直居中 */
justify-content: center; /* 水平居中 */
}
.dialog { background: #fff; padding: 16px; }
或者用 Grid:
.overlay {
position: fixed;
inset: 0;
background: rgba(0,0,0,.5);
display: grid;
place-items: center;
}
這兩種方案自適應窗口變化,不寫一行 resize 監聽,也不需要計算尺寸。如果彈層內容可能超出視窗高度,記得加上:
.overlay { overflow-y: auto; }
.dialog { max-height: 90vh; overflow-y: auto; }
否則在小屏幕上,彈層上半部分會被推出視窗且無法滾動回去。
總結:計算居中是 2010 年前後的做法,今天應該優先讓 CSS 承擔布局職責,JavaScript 只負責控制顯示與隱藏。關注點分離得越乾淨,後續維護越輕鬆。