js实现弹窗效果
使用原生JavaScript实现弹窗效果
通过document.createElement动态生成弹窗元素,结合CSS控制样式和动画
const modal = document.createElement('div');
modal.id = 'custom-modal';
modal.innerHTML = `
<div class="modal-content">
<span class="close-btn">×</span>
<p>弹窗内容</p>
</div>
`;
document.body.appendChild(modal);
const closeBtn = modal.querySelector('.close-btn');
closeBtn.onclick = () => modal.style.display = 'none';
CSS样式配置
为弹窗添加基础样式和动画效果

#custom-modal {
display: none;
position: fixed;
z-index: 999;
left: 0;
top: 0;
width: 100%;
height: 100%;
background-color: rgba(0,0,0,0.7);
}
.modal-content {
background-color: #fff;
margin: 15% auto;
padding: 20px;
width: 80%;
max-width: 600px;
animation: fadeIn 0.3s;
}
@keyframes fadeIn {
from {opacity: 0;}
to {opacity: 1;}
}
显示控制函数
封装显示/隐藏弹窗的函数便于调用

function showModal() {
document.getElementById('custom-modal').style.display = 'block';
}
function hideModal() {
document.getElementById('custom-modal').style.display = 'none';
}
// 点击弹窗外部区域关闭
window.onclick = function(event) {
if (event.target == modal) {
hideModal();
}
}
使用HTML5 dialog元素
现代浏览器支持的更简洁的实现方式
<dialog id="dialog">
<p>弹窗内容</p>
<button onclick="document.getElementById('dialog').close()">关闭</button>
</dialog>
<script>
// 显示弹窗
document.getElementById('dialog').showModal();
// 普通显示(非模态)
document.getElementById('dialog').show();
</script>
第三方库实现
使用SweetAlert2库快速创建美观弹窗
<script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
<script>
Swal.fire({
title: '自定义弹窗',
text: '这是使用SweetAlert2创建的弹窗',
icon: 'success',
confirmButtonText: '确定'
});
</script>
每种方法适用于不同场景:原生实现最灵活但代码量较大,dialog元素简洁但兼容性需考虑,第三方库能快速实现复杂效果但增加项目依赖。根据具体需求选择最合适的实现方案。






