移动端弹窗滚动时window窗体也一起滚动的解决办法

时间:2023-03-09 14:33:34
移动端弹窗滚动时window窗体也一起滚动的解决办法

在做移动端项目的时候发现,如果弹窗的内容很多很长,在滑动弹窗时,蒙层下面的window窗体也会跟着一起滚动,这样带来很差的视觉体验:
当时也想了很多办法,比如判断滑动的元素,如果是弹窗里面的元素则禁止window的滚动,如果不是,则window可以滚动

虽然在滑动弹窗的时候window体不滚动,但是当滑到弹窗边缘的时候,window体依然滚动,后来小组长想出了一个办法

即:在弹出弹窗的时候,设置window最外层定位为fixed,这样window便不会滚动了,在关闭弹窗的时候,设置window体定位为static,window便可重新滚动。

代码如下:

HTML代码:

<div class="demo">
<div class="btn">点击弹出弹窗</div>
<p class="bottom-elem">底部元素</p>
</div>
<div class="dialog-wrap">
<div class="dialog">
<div class="close-btn">点击关闭弹窗</div>
<p class="dialog-bottom">底部元素</p>
</div>
<div class="layer"></div>
</div>

CSS代码:

.btn{
width: 180px;
height: 40px;
background: #ff6677;
text-align: center;
line-height: 40px;
}
.bottom-elem{
margin-top: 1500px;
}
.dialog-wrap{
display: none;
position: fixed;
width: 100%;
height: 100%;
top:;
left:;
z-index:;
}
.dialog{
position: absolute;
top: 50%;
left: 50%;
width: 450px;
height: 500px;
background: #fff;
transform: translate(-50%,-50%);
z-index:;
overflow: auto;
font-size: 26px;
}
.dialog-bottom{
margin-top: 500px;
}
.layer{
position: fixed;
top:;
left:;
width: 100%;
height: 100%;
background: rgba(0,0,0,.65);
z-index:;
}
.close-btn{
width: 150px;
height: 50px;
background: #e8db14;
text-align: center;
line-height: 50px;
font-size: 20px;
}

JS代码:

$('.btn').on('tap',function(){
$('.dialog-wrap').css('display','block');
$('.demo').css('position','fixed');
}); $('.close-btn').on('tap',function(){
$('.dialog-wrap').css('display','none');
$('.demo').css('position','static');
});

效果如图:

移动端弹窗滚动时window窗体也一起滚动的解决办法移动端弹窗滚动时window窗体也一起滚动的解决办法

如上所示,无论弹窗滑到顶部还是底部,背景window窗体都不滑动。

虽然解决了问题,但是这样的写法有点投机取巧,后续需要想想更周全更高级的方法。

by新手小白的记录