如何检测JavaScript中的滑动?

时间:2018-11-07 15:20:39

标签: javascript html

我想用js做简单的游戏。但是为此,我想让用户通过在屏幕上向上/向下/向右/向左滑动手指/光标来进行播放。有一个简单的方法可以做到吗?

1 个答案:

答案 0 :(得分:2)

您可以尝试一下。非常简单易懂。

  var container = document.querySelector("CLASS OR ID FOR WHERE YOU WANT TO DETECT SWIPE");

  container.addEventListener("touchstart", startTouch, false);
  container.addEventListener("touchmove", moveTouch, false);

  // Swipe Up / Down / Left / Right
  var initialX = null;
  var initialY = null;

  function startTouch(e) {
    initialX = e.touches[0].clientX;
    initialY = e.touches[0].clientY;
  };

  function moveTouch(e) {
    if (initialX === null) {
      return;
    }

    if (initialY === null) {
      return;
    }

    var currentX = e.touches[0].clientX;
    var currentY = e.touches[0].clientY;

    var diffX = initialX - currentX;
    var diffY = initialY - currentY;

    if (Math.abs(diffX) > Math.abs(diffY)) {
      // sliding horizontally
      if (diffX > 0) {
        // swiped left
        console.log("swiped left");
      } else {
        // swiped right
        console.log("swiped right");
      }  
    } else {
      // sliding vertically
      if (diffY > 0) {
        // swiped up
        console.log("swiped up");
      } else {
        // swiped down
        console.log("swiped down");
      }  
    }

    initialX = null;
    initialY = null;

    e.preventDefault();
  };

参考: https://www.kirupa.com/html5/detecting_touch_swipe_gestures.htm