在 iPhone 和 Android 上通过 JavaScript 检测手指滑动 [英] Detect a finger swipe through JavaScript on the iPhone and Android
本文介绍了在 iPhone 和 Android 上通过 JavaScript 检测手指滑动的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何使用 JavaScript 检测用户在网页上向某个方向滑动手指?
How can you detect that a user swiped his finger in some direction over a web page with JavaScript?
我想知道是否有一种解决方案可以同时适用于 iPhone 和 Android 手机上的网站.
I was wondering if there was one solution that would work for websites on both the iPhone and an Android phone.
推荐答案
简单的 vanilla JS 代码示例:
Simple vanilla JS code sample:
document.addEventListener('touchstart', handleTouchStart, false);
document.addEventListener('touchmove', handleTouchMove, false);
var xDown = null;
var yDown = null;
function getTouches(evt) {
return evt.touches || // browser API
evt.originalEvent.touches; // jQuery
}
function handleTouchStart(evt) {
const firstTouch = getTouches(evt)[0];
xDown = firstTouch.clientX;
yDown = firstTouch.clientY;
};
function handleTouchMove(evt) {
if ( ! xDown || ! yDown ) {
return;
}
var xUp = evt.touches[0].clientX;
var yUp = evt.touches[0].clientY;
var xDiff = xDown - xUp;
var yDiff = yDown - yUp;
if ( Math.abs( xDiff ) > Math.abs( yDiff ) ) {/*most significant*/
if ( xDiff > 0 ) {
/* right swipe */
} else {
/* left swipe */
}
} else {
if ( yDiff > 0 ) {
/* down swipe */
} else {
/* up swipe */
}
}
/* reset values */
xDown = null;
yDown = null;
};
在 Android 中测试.
Tested in Android.
这篇关于在 iPhone 和 Android 上通过 JavaScript 检测手指滑动的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文