小程序防止页面滚动穿透

1,179 阅读1分钟

穿透表现:

穿透.webp

1、catchtouchmove

在弹窗上加catchtouchmove="return",可以避免穿透。

<view class="dialog" wx:if="{{show}}" bindtap="close" catchtouchmove="return">
  <view class="list">
    <view class="item" wx:for="{{100}}" wx:key="index">
      弹窗列表{{index}}
    </view>
  </view>
</view>

缺点:但是同时也会阻止弹窗内部的滚动

catchtouchmove.webp

因此仅适用于弹窗无滚动的情况。

2、catchtouchmove+scroll-view

若弹窗内也需要滚动,首先在弹窗上加catchtouchmove="return",避免了穿透,弹窗滚动区域再使用scroll-view包裹。

<view class="dialog" wx:if="{{show}}" bindtap="close" catchtouchmove="return">
  <view class="list">
    <scroll-view scroll-y="true" style="height: 100%;" enhanced>
      <view class="item" wx:for="{{100}}" wx:key="index">
        弹窗列表{{index}}
      </view>
    </scroll-view>
  </view>
</view>

catchtouchmove2.webp

缺点:若弹窗中有fixed定位的元素,在真机中则定位失效,元素仅出现在弹窗内,超出区域不会显示

开发工具中:

定位.webp

真机中:

真机定位.webp

因此仅适用于弹窗有滚动,且弹窗中无fixed定位元素

3、page-meta

添加page-meta标签,设置页面根节点样式page-style,页面根节点是所有页面节点的祖先节点,相当于 HTML 中的 body 节点。

在wxml文件顶部添加

<page-meta page-style="overflow: {{show ? 'hidden' : 'auto'}}" />

<view class="dialog" wx:if="{{show}}" bindtap="close">
  <view class="list">
    <view class="test">定位元素</view>
    <view class="item" wx:for="{{100}}" wx:key="index">
      弹窗列表{{index}}
    </view>
  </view>
</view>

动态控制页面滚动,弹窗打开时设为true,禁止滚动,弹窗关闭时恢复滚动。即使弹窗中有fixed定位元素,也不会有影响。

pagemeta.webp