彈出層用 CSS 寫死位置,視窗一縮放就跑掉了。比較可靠的做法是每次顯示、捲動、改變視窗大小時都重新計算一次座標。
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
});
}
top 之所以要加上 $(document).scrollTop(),是因為 position 設為 absolute,座標原點是文件而非視窗;不加上,向下捲動後彈窗就會往上飄。
left 沒有加 scrollLeft(),則是刻意讓它對齊視窗水平中心;若你的頁面會橫向捲動且希望對齊文件,記得補上。
另外,scroll 事件觸發非常頻繁,如果置中計算本身不便宜,建議加上 throttle 或 debounce,避免捲動時卡頓。