jq实现有透明遮罩的轻量级弹窗

来源:互联网 发布:趣头条提现是骗局 知乎 编辑:程序博客网 时间:2024/04/30 13:02

大致思路是:

1、先写一个弹窗的div,让其相对于浏览器来一个绝对定位(position:fixed),定在窗口可视区的中间,然后隐藏;

2、写一个遮罩层的div,给其宽高都是100%,让其相对body的绝对定位(position:absolute),定在左上角,然后隐藏;

3、给body写一个相对定位(position:relative)

4、最后用jq写点击显示,点关闭隐藏

<!DOCTYPE html><html><head><meta charset="utf-8" /><title>轻量级的弹窗</title><script type="text/javascript" src="jquery-1.11.3.js"></script><style>body {margin: 0;padding: 0;position: relative;}.div1 {height: 2000px;width: 80px;background: red;}.box {height: 300px;width: 500px;border: 2px solid #ccc;display: none;position: fixed;top: 50%;left: 50%;margin-left: -250px;margin-top: -150px;background: #fff;z-index: 3;}.title {height: 50px;background: #00b7ee;width: 100%;position: relative;}span {height: 50px;line-height: 50px;color: #fff;font-size: 18px;margin-left: 20px;}input {display: block;margin: auto;}.bg {background: #000;opacity:0.6; filter:alpha(opacity=60);position: absolute;width: 100%;height: 100%;top: 0;left: 0;z-index: 2;display: none;}img {position: absolute;top: 9px;right: 9px;cursor: pointer;}</style></head><body><input type="button" value="显示弹窗"><!-- 这里是遮罩的背景的div,宽高是100%,确保遮整个页面,它的z-index要比弹窗小 --><div class="bg"></div><pre name="code" class="html"><!-- 弹窗div,它的z-index要比弹窗大 -->
<div class="box"><div class="title"><img src="images/close.png" /><span>弹窗</span></div></div><!-- 无关紧要的div,只是让其出现下拉滚动条 --><div class="div1"></div><!-- 解读:z-index的层级关系在都是position:absolute/relative的情况下才准确,还要是同一个position:relative下 --><script>$(document).ready(function(){//点击让背景和弹窗显示$('input').click(function(){$('.bg').show();$('.box').show();});//点击让背景和弹窗隐藏$('img').click(function(){$('.bg').hide();$('.box').hide();});});</script></body></html>



0 0
原创粉丝点击