🤏 手势操作

移动端常见手势包括单击、双击、长按、滑动、缩放(pinch)、旋转等。

封装常用手势

// ===== 移动端手势工具函数 =====

// 长按事件
function onLongPress(el, callback, duration = 600) {
  let timer;
  el.addEventListener('touchstart', (e) => {
    timer = setTimeout(() => {
      callback(e);
    }, duration);
  });
  el.addEventListener('touchend', () => clearTimeout(timer));
  el.addEventListener('touchmove', () => clearTimeout(timer));
  el.addEventListener('touchcancel', () => clearTimeout(timer));
}

// 双击事件
function onDoubleTap(el, callback, interval = 300) {
  let lastTap = 0;
  el.addEventListener('touchend', (e) => {
    const now = Date.now();
    if (now - lastTap < interval) {
      callback(e);
    }
    lastTap = now;
  });
}

// 双指缩放(Pinch)
function onPinch(el, callback) {
  let lastDist = 0;
  el.addEventListener('touchstart', (e) => {
    if (e.touches.length === 2) {
      lastDist = getDistance(e.touches[0], e.touches[1]);
    }
  });
  el.addEventListener('touchmove', (e) => {
    if (e.touches.length === 2) {
      const dist = getDistance(e.touches[0], e.touches[1]);
      const scale = dist / lastDist;
      callback(scale); // scale > 1 放大,< 1 缩小
      lastDist = dist;
    }
  });
}

function getDistance(t1, t2) {
  const dx = t1.clientX - t2.clientX;
  const dy = t1.clientY - t2.clientY;
  return Math.sqrt(dx * dx + dy * dy);
}