You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在不滚动滚动条时检测滚动/触摸方向(移动端与桌面端)

跨端检测滚动/触摸方向(无需页面实际滚动)

你的代码仅适配桌面端的滚轮事件,移动端触摸滑动不会触发wheel事件,要实现跨端无滚动检测,需要分别处理桌面端滚轮事件和移动端触摸事件,同时阻止默认行为避免页面滚动:

完整实现代码

// 存储触摸起始Y坐标
let touchStartY = 0;

// 桌面端:滚轮事件处理
window.addEventListener('wheel', (e) => {
  // 阻止默认滚动,避免页面实际滚动
  e.preventDefault();
  
  const scrollDirection = e.deltaY >= 0 ? '向下' : '向上';
  // 这里添加你的方向处理逻辑
  console.log('桌面端滚动方向:', scrollDirection);
}, { passive: false }); // 必须设置passive为false,才能调用preventDefault

// 移动端:触摸起始事件
window.addEventListener('touchstart', (e) => {
  touchStartY = e.touches[0].clientY;
});

// 移动端:触摸滑动事件
window.addEventListener('touchmove', (e) => {
  e.preventDefault();
  
  const touchCurrentY = e.touches[0].clientY;
  const yDiff = touchCurrentY - touchStartY;
  
  // 过滤微小滑动,避免误判
  if (Math.abs(yDiff) > 10) {
    const touchDirection = yDiff < 0 ? '向下' : '向上';
    console.log('移动端触摸方向:', touchDirection);
    // 更新起始坐标,支持连续滑动的方向判断
    touchStartY = touchCurrentY;
  }
}, { passive: false });

关键说明

  • passive: false:现代浏览器默认touchmove和wheel事件的passive为true,无法调用preventDefault(),必须显式设置为false才能阻止页面滚动。
  • 滑动阈值:设置10px的判断阈值,过滤手指微小抖动导致的误触发。
  • 方向判断逻辑:
    • 桌面端:deltaY >= 0表示向下滚动,反之向上。
    • 移动端:触摸结束位置Y坐标小于起始位置(yDiff < 0)表示向下滑动,反之向上。

如果仅需在特定元素上检测,将事件绑定到目标元素而非window即可,减少全局影响。

内容的提问来源于stack exchange,提问作者BobK

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.25 04:22:11