在JavaScript中,创建弹窗提示通常使用alert()
、confirm()
和prompt()
这三个内置函数。以下是关于这些函数的基础概念、优势、类型、应用场景的详细解释:
alert("这是一个警告框!");
var result = confirm("你确定要继续吗?");
if (result) {
alert("你点击了确定");
} else {
alert("你点击了取消");
}
var name = prompt("请输入你的名字:", "默认名字");
if (name !== null) {
alert("你好," + name + "!");
} else {
alert("你没有输入名字");
}
HTML:
<div id="myModal" class="modal">
<div class="modal-content">
<span class="close">×</span>
<p>这是一个自定义弹窗!</p>
</div>
</div>
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 span = document.getElementsByClassName("close")[0];
// 点击按钮打开模态框
document.getElementById("openModalBtn").onclick = function() {
modal.style.display = "block";
}
// 点击关闭按钮关闭模态框
span.onclick = function() {
modal.style.display = "none";
}
// 点击模态框外部关闭模态框
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
在这个自定义弹窗示例中,我们使用了HTML来定义模态框的结构,CSS来设置样式,JavaScript来控制模态框的显示和隐藏。这种方式可以提供更灵活和丰富的用户界面体验。
领取专属 10元无门槛券
手把手带您无忧上云