【问题标题】:How to get direction and distance with jQuery Mobiles swipe event如何使用 jQuery Mobile 滑动事件获取方向和距离
【发布时间】:2013-05-07 09:48:44
【问题描述】:
在使用 jQuery Mobiles 滑动事件时,是否可以在回调函数中获取方向和距离?我在official docs 中没有找到任何相关信息。
TouchSwipe 是一个不错的选择,但我需要 jQuery Mobile 的 tap 事件表单,我不想包含两个库。
【问题讨论】:
标签:
javascript
jquery
jquery-mobile
swipe
【解决方案1】:
工作示例:http://jsfiddle.net/Gajotres/K69AJ/
这个例子是用 jQuery Mobile 事件制作的,所以它只适用于 jQuery Mobile。在 Windows 和 Android 平台上测试。
Vmouse 事件旨在弥合桌面浏览器和移动浏览器之间的差异。
还要注意这一行:
event.preventDefault();
Android 平台需要它,平台有一个令人讨厌的触摸移动检测错误。错误报告:http://code.google.com/p/android/issues/detail?id=19827
var gnStartX = 0;
var gnStartY = 0;
var gnEndX = 0;
var gnEndY = 0;
$(document).on('vmousedown', function(event){
gnStartX = event.pageX;
gnStartY = event.pageY;
event.preventDefault();
});
$(document).on('vmouseup', function(event){
gnEndX = event.pageX;
gnEndY = event.pageY;
var distance = Math.ceil(nthroot(Math.pow((gnEndX - gnStartX),2) + Math.pow((gnEndY - gnStartY),2), 2));
if(Math.abs(gnEndX - gnStartX) > Math.abs(gnEndY - gnStartY)) {
if(gnEndX > gnStartX) {
alert("Swipe Right - Distance " + distance + 'px');
} else {
alert("Swipe Left - Distance " + distance + 'px');
}
} else {
if(gnEndY > gnStartY) {
alert("Swipe Bottom - Distance " + distance + 'px');
} else {
alert("Swipe Top - Distance " + distance + 'px');
}
}
event.preventDefault();
});
function nthroot(x, n) {
try {
var negate = n % 2 == 1 && x < 0;
if(negate)
x = -x;
var possible = Math.pow(x, 1 / n);
n = Math.pow(possible, n);
if(Math.abs(x - n) < 1 && (x > 0 == n > 0))
return negate ? -possible : possible;
} catch(e){}
}
【解决方案2】:
您也可以使用hammer.js。有两个事件 - 滑动和点击。在hammer.js 中,可以获得方向和距离。点击事件也是较新的 jQuery 版本的一部分 - 您不需要仅为点击事件包含 jquery-mobile。
Documentation hammer.js
希望它对你有用。