js实现弹出框
使用原生JavaScript实现弹出框
通过window.alert()方法可以直接调用浏览器原生弹窗:
alert('这是一个简单的弹出框');
创建自定义样式弹出框
HTML结构:
<div id="customModal" 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%;
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;
}
JavaScript控制逻辑:
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";
}
}
使用第三方库实现
引入SweetAlert2库:
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
基本用法:
Swal.fire({
title: '标题',
text: '内容文本',
icon: 'success',
confirmButtonText: '确定'
});
高级用法示例:
Swal.fire({
title: '自定义弹出框',
html: '<p>支持HTML内容</p>',
showCancelButton: true,
confirmButtonColor: '#3085d6',
cancelButtonColor: '#d33',
confirmButtonText: '确认',
cancelButtonText: '取消'
}).then((result) => {
if (result.isConfirmed) {
console.log('用户点击确认');
}
});
实现带表单的弹出框
HTML结构:
<div id="formModal" class="modal">
<div class="modal-content">
<form id="modalForm">
<input type="text" placeholder="用户名">
<input type="password" placeholder="密码">
<button type="submit">提交</button>
</form>
</div>
</div>
JavaScript处理:
document.getElementById('modalForm').addEventListener('submit', function(e) {
e.preventDefault();
// 获取表单数据逻辑
console.log('表单已提交');
document.getElementById('formModal').style.display = 'none';
});
动画效果增强
为弹出框添加CSS动画:
.modal-content {
animation: modalopen 0.5s;
}
@keyframes modalopen {
from {opacity: 0; transform: translateY(-50px)}
to {opacity: 1; transform: translateY(0)}
}
响应式设计考虑
针对不同屏幕尺寸调整样式:
@media screen and (min-width: 600px) {
.modal-content {
width: 50%;
}
}






