移动端按钮长按

166 阅读1分钟

前言

识别按钮长按的关键是在 touchStart 时设置定时函数,在 touchEnd or touchMove 时取消定时器。还需要对 touchStart 和 touchEnd or touchMove 间隔太短导致定时器没有触发就被取消的情况

流程图

graph LR

A(开始)-->B[触发 touchStart 事件]-->C[setInterval 设置定时器]-->D[touchEnd or touchMove 事件]-->E{判断定时器是否被执行}
E--yes-->F[执行一次定时器的函数]
F-->G
E--no-->G(结束)

代码实现

// 延迟时间 ms
const buttonDelay = 500;
// setInterval 是否被执行
let isChange = false;
// timer 的保存,用于 clearInterval
let intervalTimer;

const handleTouchStart = () => {
  isChange = false;
  const timer = setInterval(() => {
    isChange = false;
    // 长按处理逻辑
  }, buttonDelay);
  intervalTimer = timer;
};

const handleTouchEnd = () => {
  if(!isChange) {
    // 进行一次延迟处理
  }
  clearInterval(buttonDelayTimer);
};

<button
  onTouchStart={() => handleTouchStart()}
  // 小米手机对 touchEnd 事件会不生效,需要对 touchMove 事件进行监听
  onTouchMove={() => handleTouchEnd()}
  onTouchEnd={() => handleTouchEnd()}
>
</button>