由於過去寫的是 .NET,即使轉做前端,我仍習慣用物件導向的方式來組織 JavaScript。如果你也有類似背景,對這種寫法應該不陌生。
談到 JavaScript 的物件導向,就不得不提內建的 prototype 屬性(注意,這裡指的是語言本身的 prototype,而非 prototype.js 這個函式庫)。它的作用在於可以動態地為物件擴充屬性與方法,讓我們更容易寫出可重用、可繼承的程式碼。
今天的目標很明確:點擊某個 HTML 元素時,彈出一個友善的對話框。設計上有兩個前提——一是希望大量複用這種彈窗,甚至取代系統的 alert 與 confirm;二是彈出內容要能多樣化、可自訂。
先建立一個簡單的物件,用來承載遮罩層與資訊層:
function objDIV() {
this.bgdiv;
this.infodiv;
}
先寫一個產生遮罩層的輔助函式,再把它掛到 prototype 上,讓每個實例都能呼叫:
function openBackDiv(txbdiv) {
txbdiv.bgdiv = document.createElement("div");
txbdiv.bgdiv.setAttribute("id", "overDiv");
txbdiv.bgdiv.innerHTML = "";
}
objDIV.prototype.openBG = function() {
openBackDiv(this);
document.body.appendChild(this.bgdiv);
this.bgdiv.style.display = "block";
this.bgdiv.style.width = document.documentElement.clientWidth + "px";
this.bgdiv.style.height = document.documentElement.scrollHeight + "px";
}
接著建立承載提示內容的資訊層,並設定樣式與置中:
function openLoadDiv(txbdiv) {
txbdiv.infodiv = document.createElement("div");
txbdiv.infodiv.setAttribute("id", "div_info");
txbdiv.infodiv.innerHTML = "<p>請稍等,正在處理中...</p>";
document.body.appendChild(txbdiv.infodiv);
txbdiv.infodiv.style.width = "550px";
txbdiv.infodiv.style.height = "270px";
txbdiv.infodiv.style.position = "absolute";
txbdiv.infodiv.style.background = "#fff";
txbdiv.infodiv.style.zIndex = "9999";
centerobject(); // 置中方法
}
objDIV.prototype.openLoading = function() {
this.openBG();
openLoadDiv(this);
}
既然會彈出,就得能在適當時機移除。以下方法負責關閉遮罩與資訊層:
objDIV.prototype.removeBG = function() {
if (this.bgdiv || document.getElementById("overDiv")) {
if (this.bgdiv) {
document.body.removeChild(this.bgdiv);
} else {
document.body.removeChild(document.getElementById("overDiv"));
}
}
}
objDIV.prototype.removeInfo = function() {
this.removeBG();
if (this.infodiv) {
document.body.removeChild(this.infodiv);
} else {
document.body.removeChild(document.getElementById("div_info"));
}
}
若想彈出不同內容的視窗,只要再擴充不同的 prototype 方法即可。透過這種物件導向的組織方式,彈窗邏輯變得清晰且易於複用。