為了示範方便,這裡把視窗位置固定設為 Top:200、Left:200,也就是以瀏覽器內容區左上角為原點,向右 200px、向下 200px。視窗本身的長寬則透過函式參數傳入,方便重複利用。
若要二次開發,最關鍵的一步是取得彈出層的 DOM 節點,用 getElementById 抓到 id 為 popupcontent 的元素即可:
var popUp = document.getElementById("popupcontent");
抓到節點後,位置與尺寸都能在 JavaScript 中直接調整:
popUp.style.top = "200px"; // 距內容區上方的偏移 popUp.style.left = "200px"; // 距內容區左側的偏移 popUp.style.width = w + "px"; // 視窗寬度 popUp.style.height = h + "px";// 視窗高度
接著要讓視窗可以關掉。這裡有個小技巧:宣告一個全域變數保存彈出層的原始內容。這樣一來,同一頁面上有多個內容不同的彈出層時,就不必把按鈕重複寫進每個 DIV,行為邏輯也單純得多。
if(baseText == null) baseText = popUp.innerHTML; popUp.innerHTML = baseText + '<div id="statusbar">' + '<button onclick="hidePopup();">Close window</button>' + '</div>';
最後是關閉鈕的定位。做法很簡單:只要給它設定一個向上的空白邊界,數值取決於整個彈出層的高度(設成略小於視窗高度即可)。
var baseText = null;
function showPopup(w, h){
var popUp = document.getElementById("popupcontent");
popUp.style.top = "200px";
popUp.style.left = "200px";
popUp.style.width = w + "px";
popUp.style.height = h + "px";
if(baseText == null) baseText = popUp.innerHTML;
popUp.innerHTML = baseText +
'<div id="statusbar">' +
'<button onclick="hidePopup();">Close window</button>' +
'</div>';
var sbar = document.getElementById("statusbar");
sbar.style.marginTop = (parseInt(h) - 40) + "px";
popUp.style.visibility = "visible";
}
隱藏就單純多了:取得同一個 DIV 節點,把可見性設為隱藏即可。
function hidePopup(){
var popUp = document.getElementById("popupcontent");
popUp.style.visibility = "hidden";
}
最後只要把 showPopup() 掛到對應的事件上,效果就完成了。例如滑鼠移入連結時彈出,寫成 onmouseover="showPopup(300,200)";若要改成點擊才彈出,換成 onclick 即可。