温馨提示×

ShowModalDialog如何实现弹窗交互

小樊
120
2024-10-16 13:28:13
栏目: 编程语言

ShowModalDialog 是一个用于打开模态对话框的方法,通常用于浏览器环境中的 JavaScript 代码。要实现弹窗交互,你可以使用原生的 window.alert()window.confirm()window.prompt() 方法,或者使用自定义的模态对话框。

下面是使用原生方法实现弹窗交互的示例:

  1. 使用 window.alert() 显示一个简单的提示框:
window.alert("这是一个提示框");
  1. 使用 window.confirm() 显示一个带有确认和取消按钮的对话框:
const result = window.confirm("你确定要继续吗?");
if (result) {
  console.log("用户点击了确定");
} else {
  console.log("用户点击了取消");
}
  1. 使用 window.prompt() 显示一个带有输入框的对话框,用户可以输入信息:
const input = window.prompt("请输入你的名字:");
if (input !== null) {
  console.log("用户输入的名字是:" + input);
} else {
  console.log("用户关闭了输入框");
}

如果你想要创建一个自定义的模态对话框,可以使用 HTML、CSS 和 JavaScript 来实现。下面是一个简单的自定义模态对话框示例:

HTML:

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>自定义弹窗示例</title>
  <link rel="stylesheet" href="styles.css">
</head>
<body>
  <button id="openModal">打开弹窗</button>
  <div id="myModal" class="modal">
    <div class="modal-content">
      <span id="closeModal">&times;</span>
      <p>这是一个自定义的弹窗</p>
    </div>
  </div>
  <script src="scripts.js"></script>
</body>
</html>

CSS (styles.css):

.modal {
  display: none;
  position: fixed;
  z-index: 1;
  left: 0;
  top: 0;
  width: 100%;
  height: 100%;
  overflow: auto;
  background-color: rgba(0, 0, 0, 0.4);
}

.modal-content {
  background-color: #fefefe;
  margin: 15% auto;
  padding: 20px;
  border: 1px solid #888;
  width: 80%;
}

JavaScript (scripts.js):

const openModal = document.getElementById("openModal");
const closeModal = document.getElementById("closeModal");
const modal = document.getElementById("myModal");

openModal.onclick = function () {
  modal.style.display = "block";
}

closeModal.onclick = function () {
  modal.style.display = "none";
}

window.onclick = function (event) {
  if (event.target == modal) {
    modal.style.display = "none";
  }
}

这个示例中,我们创建了一个带有关闭按钮的自定义弹窗。点击 “打开弹窗” 按钮时,弹窗会显示出来;点击关闭按钮或者点击弹窗外部区域时,弹窗会消失。你可以根据需要修改这个示例,以实现更复杂的弹窗交互。

0