js手动实现弹窗
实现基础弹窗结构
使用HTML和CSS创建一个简单的弹窗容器,默认隐藏:
<div id="customModal" class="modal">
<div class="modal-content">
<span class="close-btn">×</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%;
max-width: 500px;
}
.close-btn {
color: #aaa;
float: right;
font-size: 28px;
font-weight: bold;
cursor: pointer;
}
</style>
添加弹窗控制逻辑
通过JavaScript实现弹窗的显示/隐藏功能:

const modal = document.getElementById("customModal");
const closeBtn = document.querySelector(".close-btn");
// 显示弹窗函数
function openModal() {
modal.style.display = "block";
}
// 隐藏弹窗函数
function closeModal() {
modal.style.display = "none";
}
// 点击关闭按钮
closeBtn.addEventListener("click", closeModal);
// 点击模态框外部区域关闭
window.addEventListener("click", (event) => {
if (event.target === modal) {
closeModal();
}
});
添加动画效果
为弹窗添加淡入淡出动画效果:
.modal-content {
animation: fadeIn 0.3s;
}
@keyframes fadeIn {
from {opacity: 0; transform: translateY(-20px);}
to {opacity: 1; transform: translateY(0);}
}
实现弹窗内容动态更新
允许动态更新弹窗内容:

function showModal(content) {
const contentElement = modal.querySelector(".modal-content p");
if(contentElement) {
contentElement.textContent = content;
}
openModal();
}
// 使用示例
showModal("这是新的弹窗内容");
添加弹窗回调功能
实现关闭弹窗时的回调函数:
let modalCallback = null;
function setModalCallback(callback) {
modalCallback = callback;
}
function closeModal() {
modal.style.display = "none";
if(modalCallback) {
modalCallback();
modalCallback = null;
}
}
弹窗扩展功能
添加确认/取消按钮的对话框功能:
<div id="confirmModal" class="modal">
<div class="modal-content">
<p id="confirmMessage">确认执行此操作吗?</p>
<div class="modal-buttons">
<button id="confirmOk">确定</button>
<button id="confirmCancel">取消</button>
</div>
</div>
</div>
<style>
.modal-buttons {
text-align: right;
margin-top: 20px;
}
.modal-buttons button {
padding: 8px 16px;
margin-left: 10px;
}
</style>
function showConfirm(message, confirmCallback, cancelCallback) {
document.getElementById("confirmMessage").textContent = message;
const confirmModal = document.getElementById("confirmModal");
document.getElementById("confirmOk").onclick = function() {
confirmModal.style.display = "none";
if(confirmCallback) confirmCallback();
};
document.getElementById("confirmCancel").onclick = function() {
confirmModal.style.display = "none";
if(cancelCallback) cancelCallback();
};
confirmModal.style.display = "block";
}






