Html5页面点击遮罩层背景关闭遮罩层

2023-12-02 0 771

今天团队同事接到一个需求,需求是这样的,点击页面按钮弹出红包弹窗,显示黑色遮罩层,点击遮罩层背景和弹窗关闭按钮要关闭弹窗,于是我就做了一个Demo出来,方便以后下次自己再遇到这种需求,上代码。

html代码

页面上只有一个展示的按钮,一个ID为bg的div作为灰色背景遮罩层使用,ID为popup的div作为红包弹窗,ID为close的div作为关闭按钮。

<body>
<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>
</body>

CSS代码

css代码里面没什么技术难点,唯一要注意的是要给灰色背景的遮罩层一个绝对定位,top和lefe都为0就好了

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代码

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关闭遮罩层内容请搜索悠久资源网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持悠久资源网!

收藏 (0) 打赏

感谢您的支持,我会继续努力的!

打开微信/支付宝扫一扫,即可进行扫码打赏哦,分享从这里开始,精彩与您同在
点赞 (0)

悠久资源 HTML5 Html5页面点击遮罩层背景关闭遮罩层 https://www.u-9.cn/sheji/html5/27156.html

常见问题

相关文章

发表评论
暂无评论
官方客服团队

为您解决烦忧 - 24小时在线 专业服务