【移动端】在页面中某些区域左右滑动时,禁止页面上下滑动

454 阅读1分钟

场景

UI走查问题:

滚动问题1.png

滚动问题2.png

解决方案

在金刚区对应的组件中添加代码:

useEffect(() => {
  
  let tabsDom = document.getElementsByClassName(styles['app-tabs'])?.[0];
  tabsDom && tabsDom.addEventListener('touchmove',tabsTouchMove);
  document.addEventListener('touchmove',wrapTouchMove,{passive:false});
  //其他逻辑...

  return () => {
    tabsDom && tabsDom.removeEventListener('touchmove',tabsTouchMove);
    document.removeEventListener('touchmove',wrapTouchMove);
    //其他逻辑...
  }
}, []);

// 监听app-tabs元素的touchmove事件函数
const tabsTouchMove = (event:any) => {
  event.comesFromScrollable = true;
};

const wrapTouchMove = (event:any) => {
  if(event.comesFromScrollable){
    event.preventDefault();
  }
};

在金刚区触发touchmove事件时,给touchmove监听函数的事件添加comesFromScrollable=true标志,在文档的时间监听器上检查是否设置了标志,如有标志则阻止默认事件。

参考文章

  1. 移动端页面怎么在页面左右滑动的时候,禁止页面上下滑动
  2. 如何阻止iOS 5中touchmove事件的默认行为?