← 返回首页

jQuery实现原生Modal弹窗,无需任何UI框架

发布时间:2026-07-06 | 分类:前端 jQuery

很多项目需要弹窗功能,引入Bootstrap或者其他UI框架体积太大。今天手写一套极简jQuery弹窗,支持遮罩、点击关闭、自适应,可直接嵌入静态页面、WordPress网站。

一、完整HTML+CSS代码


<style>
.modal-mask{
    display:none;
    position:fixed;
    top:0;
    left:0;
    width:100%;
    height:100%;
    background:rgba(0,0,0,0.7);
    z-index:999;
}
.modal-box{
    width:90%;
    max-width:520px;
    background:#fff;
    color:#222;
    margin:100px auto;
    padding:24px;
    border-radius:8px;
}
.modal-close{
    float:right;
    cursor:pointer;
    font-size:22px;
}
</style>

<button class="open-modal">打开弹窗</button>

<div class="modal-mask">
    <div class="modal-box">
        <span class="modal-close">×</span>
        <h3>弹窗标题</h3>
        <p>弹窗内容区域,可以放置文字、表单、图片</p>
    </div>
</div>

二、jQuery交互脚本


<script src="https://cdn.jsdelivr.net/npm/jquery@3.7.1/dist/jquery.min.js"></script>
<script>
$(function(){
    //打开弹窗
    $('.open-modal').click(function(){
        $('.modal-mask').fadeIn();
    });
    //关闭弹窗
    $('.modal-close,.modal-mask').click(function(e){
        if(!$(e.target).closest('.modal-box').length){
            $('.modal-mask').fadeOut();
        }
    });
})
</script>

三、功能说明

1. 点击按钮弹出窗口;

2. 点击关闭按钮、遮罩空白区域均可关闭弹窗;

3. 使用fade淡入淡出动画,体验流畅;

4. 移动端自动适配宽度。

四、拓展方向

可以在此基础上改造:弹窗加载远程HTML、表单提交弹窗、图片预览弹窗、提示消息弹窗。