彈窗定位是前端常見需求,尤其要在各種螢幕解析度、捲軸位置下保持「居中」、「靠左」、「靠右」三種模式。本文提供一套完整的原生 JS + jQuery 實作,涵蓋視窗尺寸計算、捲軸偏移補償、動畫彈出與遮罩層。
function init() {
windowHeight = $(window).height();
windowWidth = $(window).width();
popHeight = $(".window").height();
popWidth = $(".window").width(); // 注意原代碼拼寫 popWidht
scrollTop = $(window).scrollTop();
scrollLeft = $(window).scrollLeft();
}
var popY = (windowHeight - popHeight) / 2 + scrollTop;
var popX = (windowWidth - popWidth) / 2 + scrollLeft;
var popY = windowHeight + scrollTop - popHeight - 10;
var popX = scrollLeft - 5;
var popY = windowHeight - popHeight + scrollTop - 10;
var popX = windowWidth - popWidth + scrollLeft - 10;
const Popup = (function() {
let $win = $(window), $doc = $(document), timeout;
function initDim() {
return {
winH: $win.height(), winW: $win.width(),
popH: $(".window").outerHeight(), popW: $(".window").outerWidth(),
scrollT: $win.scrollTop(), scrollL: $win.scrollLeft()
};
}
function animateShow($el, top, left) {
clearTimeout(timeout);
timeout = setTimeout(() => {
$el.css({top, left}).animate({opacity: "show"}, 300);
bindClose($el);
}, 300);
}
function bindClose($el) {
$el.find(".title img").one("click", function() {
$(this).closest(".window").hide("slow");
});
}
return {
center: function() {
const d = initDim();
const top = (d.winH - d.popH) / 2 + d.scrollT;
const left = (d.winW - d.popW) / 2 + d.scrollL;
animateShow($("#center"), top, left);
},
left: function() {
const d = initDim();
const top = d.winH + d.scrollT - d.popH - 10;
const left = d.scrollL - 5;
animateShow($("#left"), top, left);
},
right: function() {
const d = initDim();
const top = d.winH - d.popH + d.scrollT - 10;
const left = d.winW - d.popW + d.scrollL - 10;
animateShow($("#right"), top, left);
}
};
})();
// 綁定按鈕
$("#btn_center").click(Popup.center);
$("#btn_left").click(Popup.left);
$("#btn_right").click(Popup.right);
// 捲動時重新定位(可選)
$win.scroll(() => {
if ($(".window:visible").length) {
// 重新計算並 animate
}
});
.window {
width: 250px;
background-color: #3FF;
padding: 2px;
margin: 5px;
position: absolute;
display: none;
}
.content { height: 150px; background: #FFF; padding: 2px; font-size: 14px; overflow: auto; }
.title { padding: 2px; color: #999; font-size: 14px; }
.title img { float: right; cursor: pointer; }
<input type="button" value="彈出居中的窗口" id="btn_center">
<input type="button" value="彈出居右的窗口" id="btn_right">
<input type="button" value="彈出居左的窗口" id="btn_left">
<div class="window" id="center">
<div class="title"><img src="close.gif">標題</div>
<div class="content">內容區塊</div>
</div>
<div class="window" id="right">...</div>
<div class="window" id="left">...</div>
popWidht 拼寫錯誤,已修正為 popWidth。scroll 事件,建議在彈出時綁定、關閉時解綁。