jquery 实现简洁实用的弹窗代码

 
更多

jquery 实现简洁实用的弹窗代码,两种方法

1. position = absolute 版,这种形式的有个缺点是弹窗会随着滚动条的滚动而滚动,因此仅做参考,不建议使用

css 代码:

.oppoBg{width: 100%;height:100%;position:absolute;background-color: #000;top:0;left:0;opacity: 0.6;z-index:10;margin:0;}
.oppoBox{position:absolute;background-color: #fff;z-index: 11;margin:0;}

js 代码(下面这段 js 代码记得包在 $(function () {……}); 里面):

$('body').click(function (e) {
    //点击非#oppoBox区域关闭弹窗和背景
    if (!$(e.target).closest('#oppoBox').length) {
        $('#oppoBg,#oppoBox').addClass('hide');
    }
});
$('.nameTool').click(function (event) {
    var oppoBox = $('#oppoBox');
    $('#oppoBg').css({'height': $(document).height() + 'px'});
    oppoBox.css({'width': $(document).outerWidth() * 2 / 5 + 'px'});//这里要与下面的分开写
    oppoBox.css({'left': (($(window).width() - oppoBox.outerWidth()) / 2 + $(document).scrollLeft()) + 'px', 'top': (($(window).height() - oppoBox.outerHeight()) / 2 + $(document).scrollTop()) + 'px'});
    $('#oppoBg,#oppoBox').removeClass('hide');
    event.stopPropagation();//阻止事件冒泡
});

html 代码:

<div id="oppoBg" class="hide oppoBg"></div>
<div id="oppoBox" class="hide oppoBox">
    <div>
        <div>这是一个测试弹窗的示例!</div>
    </div>
</div>

2 . position = fixed 版,(推荐这种形式的

css 代码:

.oppoBg{width: 100%;height:100%;position:absolute;background-color: #000;top:0;left:0;opacity: 0.6;z-index:10;margin:0;}
.oppoBox{position:fixed;background-color: #fff;z-index: 11;margin:0;}

js 代码(下面这段 js 代码记得包在 $(function () {……}); 里面):

$('body').click(function (e) {
    //点击非#oppoBox区域关闭弹窗和背景
    if (!$(e.target).closest('#oppoBox').length) {
        $('#oppoBg,#oppoBox').addClass('hide');
    }
});
$('.nameTool').click(function (event) {
    var oppoBox = $('#oppoBox');
    $('#oppoBg').css({'height': $(document).height() + 'px'});
    oppoBox.css({'width': $(document).outerWidth() * 2 / 5 + 'px'});//这里要与下面的分开写
    oppoBox.css({'left': ($(window).width() - oppoBox.outerWidth()) / 2 + 'px', 'top': ($(window).height() - oppoBox.outerHeight()) / 2 + 'px'});
    $('#oppoBg,#oppoBox').removeClass('hide');
    event.stopPropagation();//阻止事件冒泡
});

html 代码:

<div id="oppoBg" class="hide oppoBg"></div>
<div id="oppoBox" class="hide oppoBox">
    <div>
        <div>这是一个测试弹窗的示例!</div>
    </div>
</div>

注意:当页面有多个弹窗的时候,最好一个 box 对应一个 bg,不要多个 box 共用一个 bg。

打赏

本文固定链接: https://www.cxy163.net/archives/3039 | 绝缘体

该日志由 绝缘体.. 于 2023年12月01日 发表在 未分类 分类下, 你可以发表评论,并在保留原文地址及作者的情况下引用到你的网站或博客。
原创文章转载请注明: jquery 实现简洁实用的弹窗代码 | 绝缘体
关键字: , , , ,

jquery 实现简洁实用的弹窗代码:等您坐沙发呢!

发表评论


快捷键:Ctrl+Enter