js实现弹窗效果
使用alert实现基础弹窗
最简单的弹窗方式是使用内置的alert()函数。这会显示一个带有指定消息和确定按钮的模态对话框。
alert("这是一个基础弹窗");
使用confirm实现确认弹窗
confirm()方法显示一个带有指定消息和确定/取消按钮的对话框。返回布尔值表示用户的选择。
const userChoice = confirm("您确定要执行此操作吗?");
if (userChoice) {
console.log("用户点击了确定");
} else {
console.log("用户点击了取消");
}
使用prompt实现输入弹窗
prompt()方法显示一个对话框,提示用户输入文本。返回用户输入的字符串或null。

const userName = prompt("请输入您的姓名", "默认值");
if (userName !== null) {
console.log(`用户输入: ${userName}`);
}
自定义HTML弹窗
创建更灵活的弹窗需要HTML和CSS配合。以下是一个基本实现:
<div id="customModal" class="modal">
<div class="modal-content">
<span class="close">×</span>
<p>这是一个自定义弹窗</p>
</div>
</div>
<style>
.modal {
display: none;
position: fixed;
z-index: 1;
left: 0;
top: 0;
width: 100%;
height: 100%;
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;
cursor: pointer;
}
</style>
<script>
const modal = document.getElementById("customModal");
const span = document.getElementsByClassName("close")[0];
function openModal() {
modal.style.display = "block";
}
span.onclick = function() {
modal.style.display = "none";
}
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
</script>
使用第三方库实现弹窗
流行的库如SweetAlert2提供了更美观的弹窗解决方案:

// 先引入SweetAlert2库
Swal.fire({
title: '自定义弹窗',
text: '使用第三方库实现的弹窗',
icon: 'success',
confirmButtonText: '确定'
});
使用dialog元素
HTML5的<dialog>元素提供了原生弹窗支持:
<dialog id="dialog">
<p>这是HTML5 dialog元素实现的弹窗</p>
<button id="closeDialog">关闭</button>
</dialog>
<button id="showDialog">显示弹窗</button>
<script>
const dialog = document.getElementById("dialog");
document.getElementById("showDialog").addEventListener("click", () => {
dialog.showModal();
});
document.getElementById("closeDialog").addEventListener("click", () => {
dialog.close();
});
</script>
弹窗动画效果
为弹窗添加CSS动画增强用户体验:
.modal-content {
animation: modalopen 0.4s;
}
@keyframes modalopen {
from {opacity: 0; transform: translateY(-50px)}
to {opacity: 1; transform: translateY(0)}
}






