SweetAlert 是一款基於 jQuery 的彈出層插件,支持普通消息提示、錯誤提示、成功提示、警告確認等多種形態。相比浏覽器原生 alert 那種生硬的白框,它的交互體驗要好得多,自動居中、自適應屏幕,桌面、平板、手機上都能正常展示,同時提供了豐富的可配置項。兼容性方面至少支持到 IE9。
調用方式也非常直覺,一個 swal 函數搞定,符合大家對 jQuery 插件的使用習慣。
先給大家演示效果:
在線預覽 源碼下載
下面是官方示例頁的代碼結構,能直觀看出各種類型的調用差異:
<h1>Sweet Alert</h1> <h2>A beautiful replacement for JavaScript's "Alert"</h2> <button class="download">Download</button> <h3>So... What does it do?</h3> <p>Here's a comparison of a standard error message. The first one uses the built-in <strong>alert</strong>-function, while the second is using <strong>sweetAlert</strong>.</p> <div class="showcase normal"> <h4>Normal alert</h4> <button>Show error message</button> <h5>Code:</h5> <pre><span class="attr">alert</span>(<span class="str">"Oops... Something went wrong!"</span>); </pre> <div class="vs-icon"></div> </div> <div class="showcase sweet"> <h4>Sweet Alert</h4> <button>Show error message</button> <h5>Code:</h5> <pre><span class="attr">sweetAlert</span>(<span class="str">"Oops..."</span>, <span class="str">"Something went wrong!"</span>, <span class="str">"error"</span>);</pre> </div> <p>Pretty cool huh? SweetAlert automatically centers itself on the page and looks great no matter if you're using a desktop computer, mobile or tablet. It's even highly customizeable, as you can see below!</p> <h3>More examples</h3> <p class="center">In these examples, we're using the shorthand function <strong>swal</strong> to call sweetAlert.</p> <ul class="examples"> <li class="message"> <div class="ui"> <p>A basic message</p> <button>Try me!</button> </div> <pre><span class="attr">swal</span>(<span class="str">"Here's a message!"</span>)</pre> </li> <li class="title-text"> <div class="ui"> <p>A title with a text under</p> <button>Try me!</button> </div> <pre><span class="attr">swal</span>(<span class="str">"Here's a message!"</span>, <span class="str">"It's pretty, isn't it?"</span>)</pre> </li> <li class="success"> <div class="ui"> <p>A success message!</p> <button>Try me!</button> </div> <pre><span class="attr">swal</span>(<span class="str">"Good job!"</span>, <span class="str">"You clicked the button!"</span>, <span class="str">"success"</span>)</pre> </li> <li class="warning confirm"> <div class="ui"> <p>A warning message, with a function attached to the "Confirm"-button...</p> <button>Try me!</button> </div>
從示例中不難歸納出它的參數規律:
只傳一個參數時,顯示一條純消息:swal("Here's a message!")。
傳兩個參數時,第二個是消息正文:swal("標題", "副文案")。
傳三個參數時,第三個決定圖標類型,可取 success、error、warning、info:swal("Good job!", "You clicked the button!", "success")。
需要確認框時,傳入的第四個參數是配置對象,裡面可以設置 showCancelButton、confirmButtonText、closeOnConfirm 等;並通過 then 或 callback 拿到用戶的選擇結果,決定後續業務邏輯。
第一,記得先引入 jQuery 再引入 SweetAlert,順序顛倒會報錯。
第二,不要把 SweetAlert 當成業務邏輯的安全保障。用戶完全可以繞過前端直接調接口,真正的權限校驗與二次確認必須在服務端完成,前端彈窗只是體驗層面的引導。
第三,涉及刪除、支付這類不可逆操作時,確認框的文案要寫清楚後果,避免用戶誤點。同時最好把確認按鈕與取消按鈕的視覺權重區分開。
第四,如果項目已經在用其他 UI 框架(Element、Ant Design 等),它們自帶的 Modal/Dialog 組件通常功能更完整、主題更統一,沒必要再引入第二套彈窗方案增加包體積。
以上就是通過代碼講解 SweetAlert 插件實現響應式提示框的完整說明,希望對大家有所幫助。