DIV CSS 佈局教程網

JavaScript 三種原生彈窗:alert、confirm、prompt 用法與自訂樣式
編輯:關於JavaScript     

原生彈窗雖然外觀樸素,但在快速除錯、簡單確認流程裡依然好用。JavaScript 內建三個:

1)alert —— 只負責告知

彈出一個警告視窗,沒有回傳值。字串中可以用 \n 換行。

alert('第一行\n第二行');

2)confirm —— 二選一

提供確定與取消兩個按鈕,回傳布林值:確定為 true,取消為 false。

var result = confirm('是否刪除!');

3)prompt —— 取得輸入

彈出輸入框,回傳使用者輸入的字串(按下取消則為 null)。第二個參數是輸入框的預設值。

var value = prompt('輸入你的名字:', '請在這裡輸入名字');

想要更好看的外觀?自己封裝一個

原生彈窗最大的問題是無法客製化,且不同瀏覽器長相各異。實務上我們會用 DOM 自己畫一個:一層遮罩 + 一個置中的容器,再覆寫 window.alert,如此一來專案裡既有的 alert() 呼叫完全不必改動。

下面的範例用純原生前綴實作,重點是遮罩高度要跟隨 document.body.scrollHeight,否則頁面捲動時遮罩會出現空白。程式碼仍有可簡化之處,先記錄於此,之後再優化。

 <script>
 window.alert = function(title, str) {
 // 遮罩層
 var shield = document.createElement("DIV");
 shield.id = "shield";
 shield.style.position = "absolute";
 shield.style.left = "0px";
 shield.style.top = "0px";
 shield.style.width = "100%";
 // 高度需對齊整個可捲動區域,避免捲動後露出縫隙
 shield.style.height = document.body.scrollHeight + "px";
 shield.style.background = "#fff";
 shield.style.textAlign = "center";
 shield.style.zIndex = "25";

 // 對話框本體
 var alertFram = document.createElement("DIV");
 alertFram.id = "alertFram";
 alertFram.style.position = "absolute";
 alertFram.style.left = "50%";
 alertFram.style.top = "50%";
 alertFram.style.marginLeft = "-225px";
 alertFram.style.marginTop = "-75px";
 alertFram.style.width = "450px";
 alertFram.style.height = "150px";
 alertFram.style.background = "#ff0000";
 alertFram.style.textAlign = "center";
 alertFram.style.lineHeight = "150px";
 alertFram.style.zIndex = "300";

 // 標題列 + 內容列 + 按鈕列
 strHtml = "<ul style=\"list-style:none;margin:0px;padding:0px;width:100%\">\n";
 strHtml += " <li style=\"background:#DD828D;text-align:left;padding-left:20px;font-size:14px;font-weight:bold;height:25px;line-height:25px;border:1px solid #F9CADE;\">" + title + "</li>\n";
 strHtml += " <li style=\"background:#fff;text-align:center;font-size:12px;height:120px;line-height:120px;border-left:1px solid #F9CADE;border-right:1px solid #F9CADE;\">" + str + "</li>\n";
 strHtml += " <li style=\"background:#FDEEF4;text-align:center;font-weight:bold;height:25px;line-height:25px;border:1px solid #e85727;\"><input type=\"button\" value=\"確 定\" onclick=\"doOk()\" /></li>\n";
 strHtml += "</ul>\n";
 alertFram.innerHTML = strHtml;

 document.body.appendChild(alertFram);
 document.body.appendChild(shield);

 var ad = setInterval("doAlpha()", 5);
 // 關閉時只隱藏,不從 DOM 移除,方便重複開啟
 this.doOk = function(){
 alertFram.style.display = "none";
 shield.style.display = "none";
 };
 alertFram.focus();
 // 期間禁止選取頁面文字,避免彈窗時誤選
 document.body.onselectstart = function(){ return false; };
 };
 </script>

使用時完全不需要改寫呼叫端,直接 alert('標題', '內容') 即可。若要在正式專案使用,建議再補上 Esc 關閉、點擊遮罩關閉,以及把行內樣式抽成 class——這幾點補完,就足以取代原生彈窗了。

以上就是三種原生彈窗的用法與自訂 alert 的實作分享。

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