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。