写在前面
- 页面弹窗组成:蒙版 + 弹窗
- 主要使用的 CSS 属性:
position
、z-Index
踩坑记录
弹窗出现之后,要求底部内容不滚动,一般可以通过设置 body
的 overflow: hidden;
实现,但是在不同手机系统或一些浏览器(如UC)中,该方法无效;所以最后采用 设置 body
的 position: fixed;
的方法。
代码
HTML部分
<div class="popup" id="popup">
<div class="cover"></div>
<div class="modal">
<div class="modal-con">
<div class="btn-close" id="btnClose">关闭</div>
<div class="modal-cont">
<h2>弹窗的标题</h2>
<p>弹窗的内容弹窗的内容弹窗的内容弹窗的内容弹窗的内容</p>
</div>
</div>
</div>
</div>
CSS部分
/* 蒙版 */
.cover {
position: fixed;
top: 0;
left: 0;
bottom: 0;
right: 0;
background: #000;
width: 100%;
height: 100%;
/* 透明度 */
opacity:0.8;
filter:alpha(opacity=80);
z-Index:999; // 比 modal 低
overflow: hidden;
}
/* 弹窗 */
.modal {
width: 70%;
position: fixed;
top: 20%;
left: 0;
right: 0;
margin: 0 auto;
z-Index:1000; // 比 cover 高
}
.btn-close {
width: 3.5rem;
height: 3.5rem;
position: absolute;
right: 0;
}
.modal-con {
width: 100%;
height: 26.4375rem;
margin: 5.375rem auto 0;
background: url("../images/bg-popup.png") no-repeat;
background-size: 100% 100%;
overflow: hidden;
}
.modal-cont {
width: 84%;
height: 22.25rem;
margin: 2.125rem auto;
overflow: hidden;
}
.modal-cont h2 {
margin-bottom: 4rem;
text-align: center;
font-size: 2.25rem;
line-height: 2.25rem;
color: #FC4F35;
}
.modal-cont p {
margin-bottom: 2rem;
font-size: 1.75rem;
line-height: 2.8125rem;
color: #fff;
}
JS部分
<script>
;(function(document, window){
// 跳出弹窗
var oModal = document.getElementById('popup')
oModal.style.display = 'block'
document.body.style.position = 'fixed' // 设置底部 body不滚动
// 关闭弹窗
document.getElementById('btnClose').addEventListener('click', function() {
oModal.style.display = 'none'
document.body.style.position = 'static' // 恢复底部 body可以滚动
})
})(document, window)
</script>