彈出層是日常開發中最常遇到的互動之一。需求變化很多:有的要在元素旁彈出,有的要固定在瀏覽器正中,有的要能拖曳,有的需要背景變暗,有的還要跟著滑鼠移動。
網上這類效果的實作很多,有原生 JavaScript 的,也有各種框架版本。但實際上很多時候用不到那麼完整的方案,所以我把功能拆開,一步一步疊加上去。以下示範皆不依賴任何框架。
先講原理:實作途徑只有兩種——動態建立與移除元素,或切換元素的顯示與隱藏。至於它長成什麼樣子,全部交給 CSS 控制。
function show(){
var oShow = document.getElementById('show');
oShow.style.display = 'block';
var oClose = document.createElement("span");
oClose.innerHTML = "×";
oShow.appendChild(oClose);
oClose.onclick = function(){
oShow.style.display = 'none';
oShow.removeChild(this);
}
}配套的結構與樣式:
#show{width:300px;height:200px;display:none;padding:1px;position:relative;
border:1px solid #4c77aa;background:#f2f7fd;margin-left:70px;zoom:1;}
#show h3{background:#4c77aa;color:#fff;font-size:14px;padding:5px;}
#show span{position:absolute;right:3px;top:3px;display:block;cursor:pointer;color:#fff;font-weight:bold;}
#show p{padding:5px;}
<a onclick="show(); return false" href="#">請猛擊我</a>
<div id="show">
<h3>彈出層標題欄</h3>
<p id="text">這裡是彈出層內容。</p>
</div>這裡有兩個細節值得學:關閉按鈕是用 createElement 動態產生並掛上事件,而不是寫死在 HTML 裡;onclick="show(); return false" 中的 return false 用來阻止連結的預設跳轉行為。
做法是先取得視窗尺寸,再減去元素尺寸除以二,把結果寫進 left 與 top。此時 position 要從 relative 改為 absolute。
function show(){
var iWidth = document.documentElement.clientWidth;
var iHeight = document.documentElement.clientHeight;
var oShow = document.getElementById('show');
oShow.style.display = 'block';
oShow.style.left = (iWidth-302)/2 + "px"; // 水平居中
oShow.style.top = (iHeight-202)/2 + "px"; // 垂直居中
var oClose = document.createElement("span");
oClose.innerHTML = "×";
oShow.appendChild(oClose);
oClose.onclick = function(){
oShow.style.display = 'none';
oShow.removeChild(this);
}
}這裡的 302 與 202 是元素的實際寬高(300×200 加上 border 與 padding)。硬編碼數字不優雅,實務上建議改用 offsetWidth/offsetHeight 動態讀取。
需要一個鋪滿整個視窗的半透明層,並讓它與關閉按鈕共用同一個關閉函式。
function show(){
var iWidth = document.documentElement.clientWidth;
var iHeight = document.documentElement.clientHeight;
var bgObj = document.createElement("div"); // 建立背景層
bgObj.setAttribute("id", "bgbox");
bgObj.style.width = iWidth + "px";
bgObj.style.height = Math.max(document.body.clientHeight, iHeight) + "px";
document.body.appendChild(bgObj);
var oShow = document.getElementById('show');
oShow.style.display = 'block';
oShow.style.left = (iWidth-302)/2 + "px";
oShow.style.top = (iHeight-202)/2 + "px";
var oClosebtn = document.createElement("span");
oClosebtn.innerHTML = "×";
oShow.appendChild(oClosebtn);
function oClose(){
oShow.style.display = 'none';
oShow.removeChild(oClosebtn);
document.body.removeChild(bgObj);
}
oClosebtn.onclick = oClose;
bgObj.onclick = oClose; // 點遮罩也能關閉
}遮罩的樣式,並用 z-index 排出層次:
#show{ position:absolute; z-index:11; /* 其餘同上 */ }
#bgbox{position:absolute;left:0;top:0;background:#000;
filter:alpha(opacity=30);opacity:0.3;z-index:10}Math.max(document.body.clientHeight, iHeight) 這一行是為了處理頁面內容比視窗高的情況,確保遮罩能完整覆蓋整個可捲動區域。
鍵盤事件在不同瀏覽器下的寫法有差異,需要一個相容的取事件函式:
function getEvent(){
return window.event || arguments.callee.caller.arguments[0];
}
document.onkeyup = function(){
var event = getEvent();
if (event.keyCode == 27){ oClose(); }
}27 就是 Esc 鍵的 keyCode。注意 oClose 必須定義在這個監聽器所及的 scope 內,實作時建議把它整理在同一個 function 裡。
var moveX = 0, moveY = 0, moveTop = 0, moveLeft = 0, moveable = false;
var docMouseMoveEvent = document.onmousemove;
var docMouseUpEvent = document.onmouseup;
titleBar = document.getElementById('titlebar');
titleBar.onmousedown = function() {
var evt = getEvent();
moveable = true;
moveX = evt.clientX;
moveY = evt.clientY;
moveTop = parseInt(oShow.style.top);
moveLeft = parseInt(oShow.style.left);
document.onmousemove = function() {
if (moveable) {
var evt = getEvent();
var x = moveLeft + evt.clientX - moveX;
var y = moveTop + evt.clientY - moveY;
// 限制在視窗範圍內,避免拖出畫面
if (x > 0 && (x + 302 < iWidth) && y > 0 && (y + 202 < iHeight)) {
oShow.style.left = x + "px";
oShow.style.top = y + "px";
}
}
};
document.onmouseup = function () {
if (moveable) {
document.onmousemove = docMouseMoveEvent;
document.onmouseup = docMouseUpEvent;
moveable = false;
moveX = 0; moveY = 0; moveTop = 0; moveLeft = 0;
}
};
}拖曳的標準套路是這樣:在 mousedown 時記下滑鼠起始位置與元素起始位置,在 mousemove 時計算位移差值並更新座標,在 mouseup 時還原事件處理器並清除狀態。最後記得把標題欄的 CSS 加上 cursor:move,並給 h3 一個 id 為 titlebar。
這五個階段構成了彈出層的完整骨架。若要繼續打磨,可以考慮:用 <div> 建立/移除改為 class 切換以便保留狀態、加入淡入淡出過渡、實作 focus 陷阱與 role="dialog" 等無障礙屬性、鎖定背景捲動、以及處理多層彈出時的 z-index 管理。這些細節才是決定一個彈出層「好不好用」的關鍵。
歡迎多提改進意見,一起討論。