瀏覽器原生的 alert 和 confirm 樣式無法定制、會阻塞整個頁面、還無法預知用戶會點哪個按鈕。下面這個組件用 jQuery 實現了同等的交互能力,並且支持自定義外觀和回調函數。
<script type="text/javascript" src="js/jquery-1.7.1.min.js"></script> <!--[if IE 6]> <script type="text/javascript" src="js/iepngfix_tilebg.js"></script> <![endif]-->
<script type="text/javascript">
function position(elem, l, t) {
var isIE6 = !-[1,] && !window.XMLHttpRequest;
if (isIE6) {
var style = elem.style,
dom = '(document.documentElement)',
left = l - document.documentElement.scrollLeft,
top = t - document.documentElement.scrollTop;
style.position = 'absolute';
style.removeExpression('left');
style.removeExpression('top');
style.setExpression('left', 'eval(' + dom + '.scrollLeft + ' + left + ') + "px"');
style.setExpression('top', 'eval(' + dom + '.scrollTop + ' + top + ') + "px"');
} else {
elem.style.position = 'fixed';
}
}
這段是整份代碼裡最「有年代感」的部分。IE6 不支持 position: fixed,只能用 CSS expression 在每次滾動時重新計算坐標來模擬。!-[1,] 是一個判斷 IE 版本的技巧(利用 IE 對數組字面量尾逗號的解析差異)。現代項目裡這些都可以刪掉,直接 position: fixed 即可。
function scscms_alert(msg, sign, ok, can) {
var c_ = false; // 是否已經關閉窗口,避免自動關閉與手動關閉衝突
sign = sign || "";
var s = "<div id='mask_layer'></div>"
+ "<div id='scs_alert'>"
+ "<div id='alert_top'></div>"
+ "<div id='alert_bg'>"
+ "<table width='260' align='center' border='0' cellspacing='0' cellpadding='1'><tr>";
if (sign != "") {
s += "<td width='45'><div id='inco_" + sign + "'></div></td>";
}
s += "<td id='alert_txt'>" + msg + "</td></tr></table>";
if (sign == "confirm") {
s += "<a href='javascript:void(0)' id='confirm_ok'>確 定</a>"
+ "<a href='javascript:void(0)' id='confirm_cancel'>取 消</a>";
} else {
s += "<a href='javascript:void(0)' id='alert_ok'>確 定</a>";
}
s += "</div><div id='alert_foot'></div></div>";
$("body").append(s);
// 垂直居中
$("#scs_alert").css("margin-top", -($("#scs_alert").height() / 2) + "px");
// 獲取焦點,防止回車鍵無法觸發
$("#scs_alert").focus();
position(document.getElementById('mask_layer'), 0, 0);
position(document.getElementById('scs_alert'),
$(window).width() / 2, $(window).height() / 2);
// 定時自動關閉
if (typeof can == "number") {
setTimeout(function () { close_info(); }, can * 1000);
}
function close_info() {
if (!c_) {
$("#mask_layer").fadeOut("fast", function () {
$("#scs_alert").remove();
$(this).remove();
});
c_ = true;
}
}
$("#alert_ok").click(function () {
close_info();
if (typeof (ok) == "function") ok();
});
$("#confirm_ok").click(function () {
close_info();
if (typeof (ok) == "function") ok();
});
$("#confirm_cancel").click(function () {
close_info();
if (typeof (can) == "function") can();
});
// 綁定回車與 ESC 鍵
function modal_key(e) {
e = e || event;
close_info();
var code = e.which || event.keyCode;
if (code == 13 || code == 32) { if (typeof (ok) == "function") ok(); }
if (code == 27) { if (typeof (can) == "function") can(); }
}
if (document.attachEvent) {
document.attachEvent("onkeydown", modal_key);
} else {
document.addEventListener("keydown", modal_key, true);
}
}
scscms_alert(msg, sign, ok, can) 四個參數分工明確:
msg——提示內容sign——圖標類型,ok/error/warn/confirm,其中 confirm 會渲染出兩個按鈕ok——確定時的回調,用 typeof(ok) == "function" 判斷,不傳也不報錯can——一參數兩用:傳函數時是取消回調,傳數字時是自動關閉的秒數這種設計讓調用方式非常靈活:
scscms_alert("默認提示信息");
scscms_alert("成功提示信息", "ok");
scscms_alert("成功提示後回調", "ok", function () { alert("回調成功!"); });
scscms_alert("失敗提示信息", "error");
scscms_alert("警告提示信息", "warn", function () { alert("警告!"); });
scscms_alert("您喜歡此提示嗎?", "confirm",
function () { scscms_alert("您選擇了喜歡,謝謝!", "ok"); },
function () { scscms_alert("您選擇了不喜歡", "error"); });
scscms_alert("本信息3秒後自動關閉", "ok", "", 3);
1. 用字符串拼 msg 有 XSS 風險。如果 msg 的內容來自用戶輸入或服務端數據,直接拼進 innerHTML 就等於把可執行腳本放進頁面。建議對 msg 做 HTML 轉義,或者把需要高亮的部分作為獨立參數傳入。
2. 全局 id 會衝突。mask_layer、scs_alert 這些 id 是寫死的。如果同一頁面同時彈出兩個提示(比如嵌套調用),DOM 裡就會出現重複 id,選擇器行為不可預期。更穩妥的做法是每次生成唯一 id,或者用 class 加容器作用域。
3. 鍵盤監聽沒有解綁。modal_key 掛在 document 上,窗口關閉後並未移除。多次彈窗會累積多個監聽器,按一次回車觸發多次回調。關閉時應該 removeEventListener。
4. javascript:void(0) 是過時寫法。用 <button type="button"> 語義更準確,也更好控制焦點。
5. 缺少無障碍支持。彈窗應加上 role="alertdialog"、aria-modal="true"、aria-labelledby,並在關閉後把焦點還給觸發元素。否則屏幕閱讀器用戶可能完全不知道彈窗出現了。
如果是在新項目裡,與其自己造這套輪子,不如直接用成熟的對話框庫——它們已經把焦點陷阱、鍵盤導航、屏幕閱讀器支持這些邊角問題處理好了。上面這份代碼的價值,在於它清楚展示了一個提示組件需要考慮哪些維度。