alert
是 JavaScript 中的一个内置函数,用于在浏览器中显示一个模态对话框,通常用于向用户显示一条消息。当 alert
被调用时,它会暂停当前脚本的执行,直到用户关闭对话框为止。
alert
会阻塞后续代码的执行,直到对话框关闭。alert
。confirm
函数使用,获取用户的确认。alert
阻塞了后续代码的执行原因:这是 alert
的设计特性,它必须等待用户交互后才能继续执行。
解决方法:
alert
,例如错误提示。console.log
进行调试输出。// 使用 alert 显示消息
alert('这是一个 alert 对话框');
// 下面的代码会等待 alert 关闭后才执行
console.log('alert 已关闭,继续执行后续代码');
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>非阻塞消息示例</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="showModalBtn">显示消息</button>
<div id="myModal" class="modal">
<div class="modal-content">
<span class="close">×</span>
<p>这是一个非阻塞的消息框!</p>
</div>
</div>
<script>
// 获取模态框元素
var modal = document.getElementById("myModal");
// 获取按钮元素
var btn = document.getElementById("showModalBtn");
// 获取 <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";
}
}
</script>
</body>
</html>
在这个示例中,我们创建了一个简单的自定义模态框,它不会阻塞页面的其他交互,允许代码在显示消息的同时继续执行。
领取专属 10元无门槛券
手把手带您无忧上云