如何在頁面上顯示對話方塊?
在本文中,我們將學習如何使用 dialog HTML 標籤在頁面上顯示對話方塊。
對話方塊可以作為向用戶提供反饋或提示使用者輸入的有用工具。HTML 的 <dialog> 元素提供了一種在網頁上顯示對話方塊的簡便方法。<dialog> 元素並非所有瀏覽器都支援,但可以使用 JavaScript 進行 polyfill 以支援舊版瀏覽器。
讓我們透過一些示例瞭解如何在網頁上實現對話方塊。
示例 1
在此示例中,我們將建立一個 id 為 "my-dialog" 的 HTML <dialog> 元素。在 <dialog> 元素內,我們將新增標題、一些內容和關閉按鈕。我們還將新增一個 id 為 "open-dialog" 的 <button> 元素,單擊該元素將開啟對話方塊。
在 JavaScript 程式碼中,我們將使用 showModal() 方法在單擊“開啟對話方塊”按鈕時顯示對話方塊。我們還將向“關閉”按鈕新增一個事件監聽器,該監聽器將在單擊時使用 close() 方法關閉對話方塊。
檔名:index.html
<html lang="en"> <head> <title>How to display a dialog box in the page?</title> </head> <body> <h3>How to display a dialog box in the page?</h3> <button id="open-dialog">Open Dialog</button> <dialog id="my-dialog"> <h2>Dialog Box Title</h2> <p>Dialog Box Content</p> <button id="close-dialog">Close</button> </dialog> <script> const openButton = document.getElementById('open-dialog'); const dialog = document.getElementById('my-dialog'); const closeButton = document.getElementById('close-dialog'); openButton.addEventListener('click', () => { dialog.showModal(); }); closeButton.addEventListener('click', () => { dialog.close(); }); </script> </body> </html>
示例 2
在此示例中,我們將遵循上述程式碼模式,並使用 window prompt 和 confirm API 顯示對話方塊。
檔名:index.html
<html lang="en"> <head> <title>How to display a dialog box in the page?</title> </head> <body> <h3>How to display a dialog box in the page?</h3> <button onclick="showPrompt()">Open Dialog using prompt</button> <button onclick="showPrompt()">Open Dialog using confirm</button> <script> function showPrompt() { const result = prompt("Enter your name:"); if (result !== null) { alert("Hello, " + result + "!"); } } function showConfirmation() { const result = confirm("Are you sure you want to delete this item?"); if (result === true) { alert("Item deleted successfully!"); } else { alert("Deletion canceled."); } } </script> </body> </html>
結論
在本文中,我們學習瞭如何使用原生的 dialog HTML 元素及其 showModal 和 close 方法在網頁上顯示對話方塊。在第一個示例中,我們建立了一個基本的對話方塊,在第二個示例中,我們使用了 window confirm 和 prompt API。對話方塊有很多實際用途,例如確認對話方塊、資訊顯示對話方塊或資訊收集對話方塊。它們還可以用於登入或身份驗證目的。例如,當用戶單擊“登入”按鈕時,可能會出現一個對話方塊來收集其憑據,從而提供更集中和直觀的登入體驗。
廣告