如何检测 JavaScript 中的滑动? [英] How to detect swipe in JavaScript?

查看:31
本文介绍了如何检测 JavaScript 中的滑动?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to make simple game in js. But for that I want to user play by swiping finger/cursor on the screen, up / down / right / left. There is a simple way to make that?

推荐答案

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

You can try this. Very simple and easy to understand.

  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

这篇关于如何检测 JavaScript 中的滑动?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆