js实现页面弹窗
使用原生JavaScript实现弹窗
创建一个基础的HTML结构,包含触发弹窗的按钮和弹窗内容
<button id="openModal">打开弹窗</button>
<div id="myModal" 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("myModal");
const btn = document.getElementById("openModal");
const span = document.getElementsByClassName("close")[0];
btn.onclick = function() {
modal.style.display = "block";
}
span.onclick = function() {
modal.style.display = "none";
}
window.onclick = function(event) {
if (event.target == modal) {
modal.style.display = "none";
}
}
使用第三方库实现弹窗(以SweetAlert2为例)
安装SweetAlert2库
npm install sweetalert2
在项目中引入并使用
import Swal from 'sweetalert2'
Swal.fire({
title: '弹窗标题',
text: '这里是弹窗内容',
icon: 'success',
confirmButtonText: '确定'
})
实现带表单的弹窗
HTML结构
<button id="showForm">显示表单弹窗</button>
<div id="formModal" class="modal">
<div class="modal-content">
<span class="close">×</span>
<form id="myForm">
<input type="text" placeholder="用户名">
<input type="password" placeholder="密码">
<button type="submit">提交</button>
</form>
</div>
</div>
JavaScript处理表单提交
const formModal = document.getElementById("formModal");
const formBtn = document.getElementById("showForm");
const formClose = formModal.getElementsByClassName("close")[0];
const myForm = document.getElementById("myForm");
formBtn.onclick = function() {
formModal.style.display = "block";
}
formClose.onclick = function() {
formModal.style.display = "none";
}
myForm.onsubmit = function(e) {
e.preventDefault();
// 处理表单数据
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)}
}
实现全屏弹窗
修改CSS样式
.modal-content {
width: 100%;
height: 100%;
margin: 0;
border-radius: 0;
}






