網頁前端彈跳視窗,在使用網頁時,某些情況像是表單送出、資料確認,都需要有彈出警示或是重複確認,若彈窗夠清楚並附帶動畫效果,更能讓使用者專注於操作上,對於使用者體驗還能有加分,SweetAlert2這個彈窗套件,不僅有美觀的設計還附帶動畫,並且提供各種客製化的功能,讓網頁呈現更多元的方式來滿足需求,下面就讓我們來看看他有多強大且好用吧。
SweetAlert2 官網(有範例可以參考)
SweetAlert2 GitHub(程式原始碼)
原生JavaScript Alert
瀏覽器中的Web APIs有提供window.alert()可直接使用跳出訊息。
網頁前端彈跳視窗-SweetAlert2
步驟說明
- 引入套件CSS、Javascript
– CSS 放置於 <head></head> 內
– JavaScript 放置於 </body> 之前 - 加入HTML、JavaScript
– 創建一個HTML Button並宣告點擊功能
– 功能名稱為showAlert()
– 在JavaScript區塊加入showAlert功能
– 加入Swal(SweetAlert實例)呼叫fire方法來執行跳出視窗功能 - 附上程式碼
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/sweetalert2.min.css" rel="stylesheet">
</head>
<body>
<button onclick="showAlert()">Click Me</button>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/sweetalert2.all.min.js"></script>
<script>
const showAlert = () => {
Swal.fire({
icon: 'success',
title: 'Hi',
text: 'Thanks for coming!',
})
}
</script>
</body>
</html>
程式碼說明
- Swal為SweetAlert2的實例
- .fire為Swal實例提供的功能來執行彈出視窗
- 宣告一個 showAlert() 方法讓事件呼叫觸發SweetAlert功能
SweetAlert fire較常用的物件變數
icon | 彈跳視窗顯示的小圖 | success, error, warning, info, question |
title | 彈跳視窗標題 | “String” |
text | 彈跳視窗內容 | “String” |
html | 彈跳視窗內容並可使用HTML語法 | “<h1>String</h1>” |
imageUrl | 彈跳視窗於上方顯示圖片 | “圖片網址” |
showConfirmButton | 是否顯示確認按鈕 | true/false |
showCancelButton | 是否顯示取消按鈕 | true/false |
showCloseButton | 是否顯示右上方 x | true/false |
position | 彈跳視窗出現位置 | top, top-start, top-end, center, center-start, center-end, bottom, bottom-start, bottom-end |
backdrop | 點擊背景是否關閉彈出視窗 | true/false |
customClass | 客製化css class | customClass: { container: ‘…’, popup: ‘…’, header: ‘…’, title: ‘…’, closeButton: ‘…’, icon: ‘…’, confirmButton: ‘…’, denyButton: ‘…’, cancelButton: ‘…’, …. } |
進階用法
客製化按鈕文字
– confirmButtonText: 用來更改確認按鈕文字
– cancelButtonText: 用來更改取消按鈕文字, 這邊使用<h1>
– 按鈕文字皆可使用HTML
Swal.fire({
icon: 'error',
title: 'WoW',
text: 'You can change button text',
showCancelButton: true,
confirmButtonText: "Yaaaaaaa",
cancelButtonText: "<h1>Close</h1>"
})
Timer自動關閉
– timer: 計時器毫秒單位
– timerProgressBar: 是否顯示進度條
– 當秒數跑完會自動關閉視窗
Swal.fire({
icon: 'warning',
title: 'Timer',
text: 'Auto close',
timer: 2000,
timerProgressBar: true,
})
點擊確認後執行其他方法
– 點擊按鈕後 fire 方法可以繼續執行其他事件
– 我們使用 .then 得到點擊的事件結果 result
(複製下方程式碼打開開發者工具console可以看到)
– 點擊 OK 按鈕 result.isConfirmed 為 true
– 並使用 if 來判斷 result.isConfirmed === true 繼續執行其他事件
– 點擊 cancel 按鈕 result.isDismissed 為 true
Swal.fire({
icon: 'question',
title: 'Are you sure',
text: 'Click OK will show another alert',
showCancelButton: true,
}).then((result) => {
console.log(result)
if(result.isConfirmed){
Swal.fire({
icon: 'success',
title: 'You did it',
text: 'I\'m new alert',
})
}
})
總結
我個人非常推薦使用SweetAlert2這個網頁彈跳視窗,各位在很多網站也能看到它的蹤影,不僅使用上非常簡單,還有多種客製化自由度高,能針對網頁提供各種不同的變化,整個跳出感覺也相當流暢,希望大家都能找一組自己善用的工具跟套件,SweetAlert2就是我常用的工具之一,大家可以留言給我,或是任何操作有疑問都可以讓我知道,我會盡量在一週內回覆你留言與透過email回覆給你,祝各位開發順利。