現成的彈出層插件很多,但有時候你就是想自己控制進出場動畫。這時候把「彈出層的基礎行為」與「動畫效果」分開設計,用覆寫方法的方式替換後者,是最靈活的結構。
var t9 = new PopupLayer({
trigger: "#ele9", // 觸發元素
popupBlk: "#blk9", // 彈出層本身
closeBtn: "#close9", // 關閉按鈕
useOverlay: true, // 是否顯示遮罩
useFx: true, // 是否啟用動畫
offsets: { x: 0, y: -41 } // 額外位移
});
t9.doEffects = function (way) {
if (way == "open") {
this.popupLayer.css({ opacity: 0.3 }).show(400, function () {
this.popupLayer.animate({
left: ($(document).width() - this.popupLayer.width()) / 2,
top: (document.documentElement.clientHeight -
this.popupLayer.height()) / 2 + $(document).scrollTop(),
opacity: 0.8
}, 1000, function () { this.popupLayer.css("opacity", 1); }
.binding(this));
}.binding(this));
} else {
this.popupLayer.animate({
left: this.trigger.offset().left,
top: this.trigger.offset().top,
opacity: 0.1
}, { duration: 500, complete: function () {
this.popupLayer.css("opacity", 1);
this.popupLayer.hide();
}.binding(this) });
}
};
開場先用 show(400, callback) 讓它淡入,同時把透明度壓到 0.3,接著在回呼裡用 animate 把 left/top 移到畫面中央、透明度升到 0.8,最後再補一段回到 1。三段式讓它「先出現、再滑到位、最後變實」,層次比單一動畫豐富。
收場則反向操作:把位置動畫回 trigger 的座標、透明度降到 0.1,動畫結束後才 hide()。彈出層從哪來、回哪去,這個細節讓互動有一致感。
left: ($(document).width() - this.popupLayer.width()) / 2,
top: (document.documentElement.clientHeight - this.popupLayer.height()) / 2
+ $(document).scrollTop()
水平用 $(document).width()(文件寬度),垂直用 documentElement.clientHeight(視窗高度)再加上捲動量。兩者基準不同:前者是文件座標,後者轉成了文件座標。在內容高度小於視窗的頁面上,這種混用會導致垂直位置偏掉。統一改用視窗座標($(window).width() / height())加 scrollTop 才是一致的做法。
jQuery 的 animate 回呼中的 this 指向動畫的元素,而不是 PopupLayer 物件。若不處理,回呼裡寫 this.popupLayer 會拿到 undefined。.binding(this) 這個寫法(出自 Prototype 的 Function.prototype.bind 概念)就是為了把 this 綁回外層物件。
今天直接用原生 bind 或箭頭函式即可:
}, 1000, () => { this.popupLayer.css("opacity", 1); });
手寫彈出層要額外處理的事不少:遮罩滾動鎖定、Esc 關閉、焦點鎖定與還原、aria-modal 標記、點擊遮罩關閉。這些在無障礙規範中是必要的,而自製版本經常遺漏。若沒有特殊動畫需求,優先使用原生 <dialog> 或 headless 函式庫(把樣式與行為完全交給你控制),會省下可觀的處理成本。