1. 使用 alert()
alert()
方法用于显示一个带有消息和一个“确定”按钮的对话框。
alert("这是一个警告弹窗!");
2. 使用 confirm()
confirm()
方法用于显示一个带有消息以及“确定”和“取消”按钮的对话框。如果用户点击“确定”,则返回 true
;如果点击“取消”,则返回 false
。
let userConfirmed = confirm("你确定要继续吗?");
if (userConfirmed) {
console.log("用户点击了确定");
} else {
console.log("用户点击了取消");
}
3. 使用 prompt()
prompt()
方法用于显示一个可提示用户输入的对话框。对话框包含一个文本输入框、一个“确定”按钮和一个“取消”按钮。如果用户点击“确定”,则返回输入框中的值;如果点击“取消”,则返回 null
。
let userInput = prompt("请输入你的名字:");
if (userInput !== null) {
console.log("用户输入了:" + userInput);
} else {
console.log("用户取消了输入");
}
4. 使用自定义 HTML 和 CSS 创建模态弹窗
有时候,内置的弹窗功能可能不够灵活或美观。你可以使用 HTML、CSS 和 JavaScript 来创建自定义的模态弹窗。
HTML:
<!-- 模态弹窗的结构 -->
<div id="myModal" class="modal">
<div class="modal-content">
<span class="close">×</span>
<p>这是一个自定义的模态弹窗。</p>
</div>
</div>
<!-- 触发弹窗的按钮 -->
<button id="openModalBtn">打开弹窗</button>
CSS:
/* 模态弹窗的样式 */
.modal {
display: none;
position: fixed;
z-index: 1;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgb(0,0,0);
background-color: rgba(0,0,0,0.4);
}
.modal-content {
background-color: #fefefe;
margin: 15% auto;
padding: 20px;
border: 1px solid #888;
width: 80%;
}
.close {
color: #aaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: black;
text-decoration: none;
cursor: pointer;
}
JavaScript:
// 获取模态弹窗
var modal = document.getElementById("myModal");
// 获取打开弹窗的按钮
var btn = document.getElementById("openModalBtn");
// 获取 <span> 元素,用于关闭模态弹窗
var span = document.getElementsByClassName("close")[0];
// 当用户点击按钮时,打开模态弹窗
btn.onclick = function() {
modal.style.display = "block";
}
// 当用户点击 <span> (x),关闭模态弹窗
span.onclick = function() {
modal.style.display = "none";
}
// 当用户点击模态弹窗外部区域时,关闭模态弹窗
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
这个自定义的模态弹窗提供了更多的灵活性和控制,你可以根据需要调整样式和功能。
希望这些示例能帮助你实现所需的弹窗功能!