如何在JavaScript中创建自定义的提示框?

如何在JavaScript中创建自定义的提示框?

在如今快节奏的世界中,保持最新的知识非常重要。通过创建自定义的提示框,可以实现这一目标。用户可以根据自己的需求获得个性化的重要信息。

语法

function Alert(message, alert type)

消息参数接收一个字符串作为输入,在警示框上显示。

警示类型 − 讯息的类型,如错误,紧急等。

警示类型参数指定要显示的讯息的类型,如错误,紧急,提示等。

示例1

我们将使用Javascript代码在HTML中生成一个警示消息框。点击一个按钮将显示警示消息。让我们创建一个简单的警示消息框,并加上一个关闭按钮来结束警示框的显示。

算法

  • 第1步 - 初始步骤是编写警示框的HTML代码和CSS样式代码。您还可以使用任何CSS代码来样式化警示框。

  • 第2步 - 在下一步中,准备JavaScript代码以设置按钮的操作,以显示警示框。为此,使用showAlert()方法,该方法接受两个参数:要显示的消息和警示类型。

  • 第3步 - 在下一步中,通过调用showAlert()函数来显示警示框。我们将在页面上的按钮上添加一个事件监听器,该监听器将在JavaScript部分直接调用该函数。

  • 第4步 - 在此步骤中,可以向警示方法添加更多参数,以自定义警示框。

<!DOCTYPE html>
<html>
<head>
   <title>
   Window alert() Method in HTML
   </title>
   <style>
      h1 {
         color: green;
      }
      h2 {
         font-family: Impact;
      }
      body {
         text-align: center;
      }
   </style>
</head>
<body>
   <h1>Customizable Alert</h1>
   <p>
      Click button to get an alert
   </p>
   <button onclick="myalert()">
      Show Alert Message
   </button>
   <script>
      function myalert() {
         alert("Hello Tutorials Point Viewersn " +
         "click OK to" +
         " close me");
      }
   </script>
</body>
</html>

示例2

让我们创建一种独特类型的自定义警示框。这个警示框将在屏幕上显示当前日期和时间。要检查时间,需要点击按钮。这样做将会出现一个警示框,上面写着日期和时间。

算法

  • 步骤1 - 通过编写HTML和CSS代码启动程序。

  • 步骤2 - 完成HTML后,编写JavaScript函数来设置警示框的基本功能。

  • 步骤3 - 编写一个脚本在警示框上显示当前日期和时间。

<!DOCTYPE html>
<html>
<head>
   <title>Custom Alert Box</title>
   <style>
      .custom-alert {
         position: fixed;
         top: 50%;
         left: 50%;
         transform: translate(-50%, -50%);
         background-color: #f1f1f1;
         border: 1px solid #ccc;
         padding: 20px;
         border-radius: 5px;
      }
      .custom-alert h2 {
         margin: 0;
      }
   </style>
</head>
<body>
   <button onclick="showCustomAlert()">Show Custom Alert</button>
   <script>
      function showCustomAlert() {
         var currentDate = new Date();
         var currentTime = currentDate.toLocaleString();
         var alertBox = document.createElement('div');
         alertBox.classList.add('custom-alert');
         var heading = document.createElement('h2');
         heading.textContent = 'Custom Alert';
         alertBox.appendChild(heading);
         var timeLabel = document.createElement('p');
         timeLabel.textContent = 'Current Time and Date: ' + currentTime;
         alertBox.appendChild(timeLabel);
         document.body.appendChild(alertBox);
      }
   </script>
</body>
</html>

结论

通过在JavaScript中创建可定制的警示框,可以通过提供更美观和有用的方式与用户进行通信,从而提高Web应用的用户体验。定制警示框的重要步骤包括为警示框本身编写HTML和CSS,并利用JavaScript根据用户输入动态设置样式属性和内容。Web开发人员在创建需要定期用户输入或通知的用户界面时应牢记这一策略。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程