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: 600px;
position: relative;
}
.close-btn {
position: absolute;
right: 15px;
top: 5px;
font-size: 24px;
cursor: pointer;
}
</style>
添加弹窗控制逻辑
通过JavaScript实现弹窗的显示/隐藏功能:

const modal = document.getElementById("customModal");
const closeBtn = document.querySelector(".close-btn");
// 显示弹窗函数
function openModal() {
modal.style.display = "block";
document.body.style.overflow = "hidden"; // 防止背景滚动
}
// 隐藏弹窗函数
function closeModal() {
modal.style.display = "none";
document.body.style.overflow = "auto";
}
// 点击关闭按钮
closeBtn.onclick = closeModal;
// 点击弹窗外部区域关闭
window.onclick = function(event) {
if (event.target === modal) {
closeModal();
}
}
添加动画效果
为弹窗添加CSS过渡动画:

.modal-content {
animation: fadeIn 0.3s;
}
@keyframes fadeIn {
from {opacity: 0; transform: translateY(-20px);}
to {opacity: 1; transform: translateY(0);}
}
实现可配置弹窗
创建更灵活的弹窗函数,支持动态内容:
function showModal(options) {
const { title, content, width, buttons } = options || {};
const modal = document.createElement('div');
modal.className = 'modal';
modal.innerHTML = `
<div class="modal-content" style="width: ${width || '80%'}">
<span class="close-btn">×</span>
${title ? `<h3>${title}</h3>` : ''}
<div class="modal-body">${content || ''}</div>
${buttons ? `<div class="modal-footer">${buttons.map(btn =>
`<button class="${btn.class || ''}">${btn.text}</button>`
).join('')}</div>` : ''}
</div>
`;
document.body.appendChild(modal);
modal.style.display = 'block';
modal.querySelector('.close-btn').onclick = () => {
document.body.removeChild(modal);
};
}
// 使用示例
showModal({
title: '提示',
content: '确认要执行此操作吗?',
buttons: [
{ text: '取消', class: 'cancel-btn' },
{ text: '确定', class: 'confirm-btn' }
]
});
弹窗类型扩展
实现不同风格的弹窗样式:
/* 警告型弹窗 */
.alert-modal .modal-content {
border-left: 5px solid #ff9800;
}
/* 确认型弹窗 */
.confirm-modal .modal-footer {
text-align: right;
padding-top: 15px;
}
.confirm-modal button {
padding: 8px 15px;
margin-left: 10px;
}
.confirm-modal .confirm-btn {
background-color: #4CAF50;
color: white;
}






