【问题标题】:How to detect swipe in JavaScript? [duplicate]如何检测 JavaScript 中的滑动? [复制]
【发布时间】:2018-11-07 15:20:39
【问题描述】:

我想用js制作简单的游戏。但是为此,我想通过在屏幕上向上/向下/向右/向左滑动手指/光标来进行用户游戏。有简单的方法吗?

【问题讨论】:

  • 你可以考虑一个库,比如HammerJS

标签: javascript html


【解决方案1】:

你可以试试这个。非常简单易懂。

  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

【讨论】:

  • 虽然此链接可能会回答问题,但最好在此处包含答案的基本部分并提供链接以供参考。如果链接页面发生更改,仅链接的答案可能会失效。
  • 谢谢!,会的
  • 哇,伙计!你太棒了!谢谢!
猜你喜欢
  • 1970-01-01
  • 2020-09-05
  • 1970-01-01
  • 2011-04-18
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-01-17
  • 1970-01-01
相关资源
最近更新 更多