今天团队同事接到一个需求,需求是这样的,点击页面按钮弹出红包弹窗,显示黑色遮罩层,点击遮罩层背景和弹窗关闭按钮要关闭弹窗,于是我就做了一个Demo出来,方便以后下次自己再遇到这种需求,上代码。
html代码
页面上只有一个展示的按钮,一个ID为bg的div作为灰色背景遮罩层使用,ID为popup的div作为红包弹窗,ID为close的div作为关闭按钮。
1 2 3 4 5 6 | < div class = "btn" id = "btn" >展示</ div > < div class = "bg" id = "bg" > < div class = "popup" id = "popup" > < div class = "close" id = "close" >X</ div > </ div > </ div > |
CSS代码
css代码里面没什么技术难点,唯一要注意的是要给灰色背景的遮罩层一个绝对定位,top和lefe都为0就好了
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | body { position : relative ; } .btn { width : 100px ; height : 40px ; line-height : 40px ; text-align : center ; margin : 20px auto 0 ; border : 1px solid #333 ; border-radius : 10px ; } .bg { width : 100% ; height : 100% ; position : fixed ; top : 0 ; left : 0 ; background-color : rgba ( 0 , 0 , 0 , . 6 ); display : none ; } .popup { width : 260px ; height : 320px ; background : red ; position : absolute ; top : 50% ; left : 50% ; transform : translate ( -50% , -50% ); border-radius : 15px ; } .popup .close { width : 30px ; height : 30px ; line-height : 30px ; text-align : center ; position : absolute ; top : -40px ; right : 0px ; border : 1px solid #999 ; border-radius : 50% ; color : #999 ; } |
JS代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 | var btn = document.getElementById( 'btn' ); var bg = document.getElementById( 'bg' ); var popup = document.getElementById( 'popup' ); var closeBtn = document.getElementById( 'close' ); // 点击展示按钮显示弹窗 btn.addEventListener( 'click' , ()=> { bg.style.display = 'block' ; }); // 点击阴影遮罩层关闭弹窗 bg.addEventListener( 'click' , (e)=> { bg.style.display = 'none' }); // 阻止冒泡事件,点击弹窗不会执行父元素的点击事件 popup.addEventListener( 'click' , (e)=> { e.stopPropagation(); }); // 点击关闭符号关闭弹窗 closeBtn.addEventListener( 'click' , (e)=> { e.stopPropagation(); bg.style.display = 'none' }) |
到此这篇关于Html5页面点击遮罩层背景关闭遮罩层的文章就介绍到这了,更多相关Html5关闭遮罩层内容请搜索IT俱乐部以前的文章或继续浏览下面的相关文章,希望大家以后多多支持IT俱乐部!