今天 团队 同事接到一个需求,需求是这样的,点击页面按钮弹出 红包 弹窗,显示黑色遮罩层,点击遮罩层背景和弹窗关闭按钮要关闭弹窗,于是我就做了一个Demo出来,方便以后下次自己再遇到这种需求,上代码。
ht ML 代码
页面上只有一个展示的按钮,一个ID为bg的div作为灰色背景遮罩层使用,ID为popup的div作为红包弹窗,ID为close的div作为关闭按钮。
<body> <div class=" BT n" id="btn">展示</div> <div class="bg" id="bg"> <div class="popup" id="popup"> <div class="close" id="close">X</div> </div> </div> </body>
CSS代码
css代码里面没什么技 术 难点,唯一要注意的是要给灰色背景的遮罩层一个绝对定位,top和lefe都为0就好了
body { pos IT ion: relative; } .btn { width: 100px; h ei ght: 40px; line-height: 40px; text-align: center ; m arg in: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); dis play : 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代码
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.stop PR opagation(); }); // 点击关闭符号关闭弹窗 closeBtn.addEventListener('click', (e)=> { e.stopPropagation(); bg.style.display = 'none' })
到此这篇关于 HTML5页面 点击遮罩层背景关闭遮罩层的 文章 就介绍到这了,更多相关Html5关闭遮罩层内容请搜索以前的文章或继续浏览下面的相关文章,希望大家以后多多支持!
总结
以上是 为你收集整理的 Html5页面点击遮罩层背景关闭遮罩层 全部内容,希望文章能够帮你解决 Html5页面点击遮罩层背景关闭遮罩层 所遇到的问题。
如果觉得 网站内容还不错, 推荐好友。
查看更多关于Html5页面点击遮罩层背景关闭遮罩层的详细内容...
声明:本文来自网络,不代表【好得很程序员自学网】立场,转载请注明出处:http://www.haodehen.cn/did211528