如何在页面上显示对话框?

htmlweb developmentfront end technology更新于 2024/11/12 13:00:17

在本文中,我们将学习如何使用 dialog HTML 标签在页面上显示对话框。

对话框可以成为向用户提供反馈或提示他们输入的有用工具。HTML <dialog> 元素提供了一种在网页上显示对话框的简便方法。并非所有浏览器都支持 <dialog> 元素,但可以使用 JavaScript 对其进行 polyfill 以支持旧版浏览器。

让我们通过一些示例来了解如何在网页上实现对话框

示例 1

在本例中,我们将创建一个 id 为"my-dialog"的 HTML <dialog> 元素。在 <dialog> 元素内,我们将添加一个标题、一些内容和一个关闭按钮。我们还将添加一个 <button> id 为"open-dialog"的元素,点击后会打开对话框。

在 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

在此示例中,我们将遵循上述代码模式,并使用窗口提示和确认 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 的确认 API 和提示 API。对话框有很多实际用途,例如确认对话框、信息显示对话框或信息收集对话框。它们也可用于登录或身份验证。例如,当用户点击"登录"按钮时,会出现一个对话框来收集用户的凭据,从而提供更专注、更直观的登录体验。


相关文章


有用资源