JavaScript中的弹框主要有三种类型:alert()
、confirm()
和prompt()
。这些弹框都是浏览器内置的,用于与用户进行简单的交互。
// 使用alert显示一条消息
alert('这是一个alert弹框');
// 使用confirm询问用户一个问题
let isConfirmed = confirm('你确定要继续吗?');
if (isConfirmed) {
console.log('用户点击了确定');
} else {
console.log('用户点击了取消');
}
// 使用prompt获取用户输入
let userInput = prompt('请输入你的名字:');
if (userInput !== null) {
console.log('用户输入了:', userInput);
} else {
console.log('用户没有输入或点击了取消');
}
优势:
应用场景:
问题1: 弹框被浏览器阻止。
问题2: 弹框样式不统一或不符合设计需求。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Custom Modal</title>
<style>
.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%;
}
.close {
color: #aaa;
float: right;
font-size: 28px;
font-weight: bold;
}
.close:hover,
.close:focus {
color: black;
text-decoration: none;
cursor: pointer;
}
</style>
</head>
<body>
<button id="openModalBtn">Open Modal</button>
<div id="myModal" class="modal">
<div class="modal-content">
<span class="close">×</span>
<p>这是一个自定义模态框!</p>
</div>
</div>
<script>
document.getElementById('openModalBtn').addEventListener('click', function() {
document.getElementById('myModal').style.display = 'block';
});
document.querySelector('.close').addEventListener('click', function() {
document.getElementById('myModal').style.display = 'none';
});
</script>
</body>
</html>
通过这种方式,你可以完全控制弹框的样式和行为,以满足更复杂的设计需求。
领取专属 10元无门槛券
手把手带您无忧上云