DIV CSS 佈局教程網

自製 JavaScript 對話框:從瀏覽器判斷到拖曳實作的完整拆解
編輯:關於JavaScript     

原生 alert() 很方便,但外觀簡陋、無法自訂,而且外殼由各瀏覽器自行實作,在 Chrome、Firefox、IE 上長得都不一樣。隨著使用者對體驗的要求提高,自建對話框幾乎成了必備技能。以下從零開始拆解一個可拖曳、支援多瀏覽器的模態對話框。

這個實作可運行於 IE6/7/8、Firefox、Chrome 等主流瀏覽器。

第一步:判斷瀏覽器類型

用幾個布林變量標記不同瀏覽器,透過 userAgent 檢測來設定。

var springweb_typeIsIE = false, springweb_typeIsGecko = false, springweb_typeIsWebkit = false;
var springweb_typeIsIE6 = false, springweb_typeIsIE7 = false, springweb_typeIsIE8 = false;
var springweb_typeIsFireFox = false, springweb_typeIsChrome = false, springweb_typeIsSafari = false;

var agent = window.navigator.userAgent;
if (agent.indexOf("MSIE 6") != -1)      { springweb_typeIsIE6 = true; springweb_typeIsIE = true; }
else if (agent.indexOf("MSIE 7") != -1) { springweb_typeIsIE7 = true; springweb_typeIsIE = true; }
else if (agent.indexOf("MSIE 8") != -1) { springweb_typeIsIE8 = true; springweb_typeIsIE = true; }
else if (agent.indexOf("Firefox") != -1){ springweb_typeIsFireFox = true; springweb_typeIsGecko = true; }
else if (agent.indexOf("Chrome") != -1) { springweb_typeIsChrome = true; springweb_typeIsWebkit = true; }
else if (agent.indexOf("Safari") != -1) { springweb_typeIsSafari = true; springweb_typeIsWebkit = true; }

這是最直白的判斷方式。現代做法應改用特性偵測——例如判斷 window.getComputedStyle 是否存在,而非依賴 UA 字串。

第二步:製作模態遮罩

模態效果的目的是讓使用者在對話框關閉前無法操作頁面其他部分。做法是鋪一層半透明黑幕,並鎖住捲軸。

document.body.style.overflowY = "hidden";
var divBackground = document.createElement("div");
divBackground.style.position = "absolute";
divBackground.style.left = "0px";
divBackground.style.top = "0px";
divBackground.style.width = "100%";
divBackground.style.height = "100%";
if (springweb_typeIsChrome || springweb_typeIsFireFox) {
    divBackground.style.backgroundColor = "rgba(0,0,0,0.7)";
} else {
    divBackground.style.backgroundColor = "#000000";
    divBackground.style.filter = "alpha(opacity=70)";
}
divBackground.style.zIndex = "99";
document.body.appendChild(divBackground);

關鍵在透明度:IE 舊版只認自己的 filter 濾鏡,其他瀏覽器則用 CSS3 的 rgba。用 zIndex 分層,遮罩在下(99),對話框在上(100)。

第三步:建立對話框主體

先依訊息長度估算尺寸,再置中定位。

var dialogWidth = 260, dialogHeight = 120, fontSize = 14;
var lineWidth = document.body.clientWidth * 0.7;
if ((fontSize * msg.length) < lineWidth) {
    dialogWidth = parseInt(fontSize * msg.length) + 50;
} else {
    dialogWidth = parseInt(lineWidth);
    dialogHeight += parseInt(((fontSize * msg.length) / lineWidth) * fontSize);
}
divDialog.style.width = dialogWidth + "px";
divDialog.style.height = dialogHeight + "px";
divDialog.style.position = "absolute";
divDialog.style.border = "1px solid #C0D7FA";
divDialog.style.borderRight = "2px outset #DEDEDE";
divDialog.style.borderLeft = "2px outset #DEDEDE";
divDialog.style.left = ((document.body.clientWidth / 2) - (dialogWidth / 2)) + "px";
divDialog.style.top = ((document.body.clientHeight / 2) - (dialogHeight / 2)) + "px";
divDialog.style.zIndex = "100";

這裡的尺寸估算是粗糙的字元數乘字級,中文與英文寬度不同,換行時機也不精準。實務上更好的做法是先用 max-width 約束寬度、讓內容自然換行,再由瀏覽器算出實際高度。

第四步:標題欄與拖曳

var divHead = document.createElement("div");
if (title != undefined) divHead.innerHTML = title;
else divHead.appendChild(document.createTextNode("消息"));

divHead.style.width = "100%";
divHead.style.height = "25px";
divHead.style.lineHeight = "25px";
divHead.style.fontSize = "14px";
divHead.style.fontWeight = "bold";
divHead.style.borderBottom = "1px outset #8989FF";
divHead.style.color = "white";
divHead.style.textIndent = "10px";
divHead.style.backgroundColor = "blue";
divHead.style.backgroundImage = "url('" + springweb_basePath + "/images/headbg.png')";
divHead.style.cursor = "move";

divHead.onmousedown = function(){ divDialog.dragging = true; };
divHead.onmouseup   = function(){ divDialog.dragging = false; };

document.body.onmousemove = function(e) {
    if (!divDialog.dragging) return;
    e = e || window.event;
    var mouseX, mouseY;
    if (e.pageX || e.pageY) {
        mouseX = e.pageX; mouseY = e.pageY;
    } else {
        mouseX = e.clientX + document.body.scrollLeft - document.body.clientLeft;
        mouseY = e.clientY + document.body.scrollTop  - document.body.clientTop;
    }
    divDialog.style.left = (mouseX - dialogWidth * 0.4) + "px";
    divDialog.style.top  = (mouseY - 10) + "px";
};
divDialog.appendChild(divHead);

這裡有個值得學的技巧:為 DOM 元素動態加上 dragging 屬性來記錄拖曳狀態。JavaScript 中對物件新增屬性不需要事先宣告,直接 obj.dragging = true 即可。

但要誠實指出這段程式的兩個缺點。其一,拖曳位置用的是固定偏移量(寬度的 0.4 與 10),沒有計算滑鼠按下時與對話框左上角的實際相對位置,所以每次開始拖動對話框都會「跳」一下。正確做法是在 mousedown 時記錄 e.pageX - dialog.offsetLeft 這個差值,mousemove 時再減回去。其二,拖曳時沒有邊界檢查,對話框可能被拖出視窗而無法找回。

第五步:內容區與關閉按鈕

var divContent = document.createElement("div");
divContent.style.textAlign = "center";
divContent.style.padding = "15px";
divContent.style.fontSize = "12px";
divContent.style.height = parseInt(dialogHeight - (springweb_typeIsIE ? 25 : 55)) + "px";
divContent.style.backgroundColor = "#ffffff";

// 依瀏覽器套用不同的漸變實作
if (springweb_typeIsIE6 || springweb_typeIsIE7 || springweb_typeIsIE8) {
    divContent.style.filter =
        "progid:DXImageTransform.Microsoft.Gradient(gradientType=1,startColorStr=#FFFFFF,endColorStr=#C2E2F8)";
} else if (springweb_typeIsFireFox) {
    divContent.style.backgroundImage =
        "-moz-linear-gradient(left,rgba(255,255,255,1),rgba(194,226,248,1))";
} else if (springweb_typeIsWebkit) {
    divContent.style.backgroundImage =
        "-webkit-gradient(linear,0% 0%,100% 100%,from(#FFFFFF),to(#000000))";
}

divContent.innerHTML = msg + "<br /><br />";
divDialog.appendChild(divContent);

var closeButton = document.createElement("img");
closeButton.style.cursor = "hand";
closeButton.setAttribute("src", springweb_basePath + "/images/okButton.png");
closeButton.setAttribute("alt", "確定");
closeButton.onclick = function() {
    document.body.removeChild(divBackground);
    document.body.removeChild(divDialog);
    document.body.style.overflowY = "";      // 記得還原捲軸
};
divContent.appendChild(closeButton);

divDialog.focus();
document.body.appendChild(divDialog);

漸變同樣是三套寫法:IE 用微軟的 Gradient 濾鏡,Firefox 用 -moz-linear-gradient,Webkit 用 -webkit-gradient(原程式碼中此處有拼字誤植,已修正)。今天只需寫標準的 linear-gradient 即可。

這個版本還缺什麼

關閉時的資源清理不完整。只有移除 DOM 節點是不夠的——挂在 document.body 上的 mousemove 監聽器仍然存活,且它閉包著 divDialog,會造成記憶體無法回收。應在關閉時把監聽器一併移除。

不支援 ESC 關閉與鍵盤操作。模態對話框應該監聽 keydown,讓 ESC 能關閉、Tab 焦點被限制在對話框內,否則鍵盤使用者會「游標逃逸」到背後的頁面。

缺少 aria 屬性。加上 role="dialog" 與 aria-modal="true",螢幕閱讀器才能正確理解這是模態對話。

這些並非吹毛求疵,而是自建 UI 元件時最常被忽略的部分。互動功能做起來只要幾十行,但要做對可存取性與資源管理,往往才是真正花時間的地方。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved