前言
最近在做小程序开发、测试反馈了个问题:期望在有弹窗出现时, 下面的内容不允许滚动. 卑微的我只能去想办法解决下, 那么该怎么解决呢?
实现方案
- 小程序自带-> catchtouchmove;
- 使用position:fixed禁止页面滚动;
1. 小程序自带-> catchtouchmove实现demo
注意事项:
a. 在微信开发者工具测试是没有用的, 需要在真机上查看效果[∵触摸事件];
b. catchtouchmove若定义成方法、则必须申明、否则控制台会有警告[空函数即可];
c. 经测试, catchtouchmove的值只要是非空字符即可, 这也是为什么在网上看到会有写个true也可阻止页面滚动的原因;
Tips: 以下代码可直接拷贝查看效果
// wxml
<view class="index">
<!-- 页面结构区 -->
<view class="content"></view>
<view class="btn" bind:tap="showModal">点我显示弹窗</view>
</view>
<!-- 简易弹窗组件: 1.点击遮罩关闭弹窗; 2. 遮罩出现时禁止底层页面滚动; -->
<view class="modal-layer" wx:if="{{showModal}}" bindtap="closeModal" catchtouchmove="prevent">
<view class="modal-content">弹窗内容区</view>
</view>
// wxss
/* 通过设定较大的height模拟内容区数据太多、需要滚动 */
.content{
height: 2000rpx;
overflow: auto;
}
.btn{
padding: 10rpx 40rpx;
background: aquamarine;
color: #ffffff;
font-size: 28rpx;
margin: 0 auto;
}
.modal-layer{
position: fixed;
width: 100%;
height: 100%;
top: 0;
left: 0;
background-color: rgba(0, 0, 0, 0.7);
z-index: 100;
}
.modal-content{
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
width: 400rpx;
height: 400rpx;
color: black;
background-color: #ffffff;
z-index: 101;
}
// js
const app = getApp()
Page({
data: {
showModal: false,
},
// 出现弹窗
showModal() {
this.setData({
showModal: true
})
},
// 关闭弹窗
closeModal() {
this.setData({
showModal: false
})
},
// 空方法、避免出现警告
prevent() { }
})
接下来在真机上看看效果:
这种方法是比较推荐的方法、当然也还有其它方法可以实现,下面就再说一种叭~
2. 使用position:fixed禁止页面滚动;
实现原理:
在弹窗出现时禁止页面滚动;在弹窗关闭时放开页面滚动;
注意事项:
a. 此种做法视觉上面有点缺陷: 虽说页面禁止滚动了、But还是能看到滚动条滚来滚去的, 真让人讨厌.
// 整体沿用上面的demo, 以下仅针对需要改动的部分做说明
// wxml
<view class="index {{showModal? 'fixed':''}}">
<scroll-view class="content"></scroll-view>
<view class="btn" bind:tap="showModal">点我显示弹窗</view>
</view>
<view class="modal-layer" wx:if="{{showModal}}" bindtap="closeModal">
<view class="modal-content">弹窗内容区</view>
</view>
// wxss
/*
top:0 不建议写:若本来在页面底部、然后显示弹窗的同时会因top:0导致底层滚动回顶部 -> 不合理
*/
.fixed {
position: fixed;
left: 0;
right: 0;
bottom: 0;
}