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

如何实现触摸向下滚动页面时不触发横向可移动块的触摸事件?

实现仅横向触摸滑动时移动块,纵向滚动不触发

需求:有一个可沿X轴移动的块,要求触摸向下滚动页面时块不移动,只有左右触摸滑动时才让块移动。

原代码问题

原代码只要触发touchmove事件就会移动块,无法区分横向滑动和纵向滚动操作,导致页面滚动时块也会跟着移动。

修改后的代码

HTML(无需修改)

<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>Swipe</title>
</head>
<body>
  <h1 class='h1'>OPEN MOBILE VIEW IN DEVTOOLS</h1>
  <div class="container">
    <div class='movable-block'>
      <span class="movable-block__title">Movable block</span>
      <div class="movable-block__line"></div>
    </div>
  </div>
</body>
</html>

JavaScript

const container = document.getElementsByClassName('container')[0];
const movableBlock = document.getElementsByClassName('movable-block')[0];
let startX, startY;

// 触摸开始时记录初始坐标,并移除旧的touchmove监听
container.addEventListener('touchstart', (e) => {
    startX = e.touches[0].clientX;
    startY = e.touches[0].clientY;
    // 移除之前的touchmove监听,避免重复绑定
    container.removeEventListener('touchmove', handleTouchMove);
    container.addEventListener('touchmove', handleTouchMove);
});

function handleTouchMove(event) {
    const currentX = event.touches[0].clientX;
    const currentY = event.touches[0].clientY;
    const diffX = Math.abs(currentX - startX);
    const diffY = Math.abs(currentY - startY);

    // 判定为横向滑动时才移动块(横向偏移大于纵向,且超过最小阈值避免误触)
    if (diffX > diffY && diffX > 10) {
        movableBlock.style.left = currentX - movableBlock.offsetWidth / 2 + 'px';
    }
}

核心逻辑说明

  1. 记录初始触摸坐标:在touchstart事件中记录触摸点的初始X、Y坐标,作为后续判断滑动方向的基准。
  2. 区分滑动方向:在touchmove中计算当前触摸点与初始点的横向、纵向偏移量,当横向偏移量大于纵向偏移量(且超过10px阈值避免误触)时,判定为横向滑动,才更新块的位置。
  3. 避免重复绑定事件:每次touchstart时先移除之前的touchmove监听,防止多次触发导致块移动异常。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.25 19:57:38