在JavaScript中,弹出消息框主要通过两种方式实现:alert()
和 confirm()
,还有 prompt()
用于获取用户输入。
alert("这是一个警告消息!");
let userConfirmed = confirm("你确定要继续吗?");
if (userConfirmed) {
console.log("用户点击了确定");
} else {
console.log("用户点击了取消");
}
let userInput = prompt("请输入你的名字:");
if (userInput !== null) {
console.log("用户输入了:" + userInput);
} else {
console.log("用户没有输入任何内容");
}
以下是一个简单的自定义弹出框示例:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Custom Alert</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>
<div id="myModal" class="modal">
<div class="modal-content">
<span class="close">×</span>
<p>这是一个自定义警告消息!</p>
</div>
</div>
<button onclick="showModal()">显示自定义警告框</button>
<script>
function showModal() {
document.getElementById("myModal").style.display = "block";
}
document.getElementsByClassName("close")[0].onclick = function() {
document.getElementById("myModal").style.display = "none";
}
window.onclick = function(event) {
if (event.target == document.getElementById("myModal")) {
document.getElementById("myModal").style.display = "none";
}
}
</script>
</body>
</html>
这个示例展示了如何使用HTML、CSS和JavaScript创建一个简单的自定义弹出框,并通过按钮触发显示和隐藏。
领取专属 10元无门槛券
手把手带您无忧上云