如何通过jQuery Mobiles滑动事件获得方向和距离 [英] How to get direction and distance with jQuery Mobiles swipe event

查看:65
本文介绍了如何通过jQuery Mobiles滑动事件获得方向和距离的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用jQuery Mobiles滑动事件时,是否可以获得回调函数中的方向和距离?我在官方文档中找不到任何相关内容。

Is it possible to get the direction and the distance in a callback function when using jQuery Mobiles swipe event? I've found nothing about it in the official docs.

TouchSwipe 是一个不错的选择,但我需要点击事件形式jQuery Mobile,我不想包含两个库。

TouchSwipe is a good alternative, but i need the tap event form jQuery Mobile and i don't want to include two libraries.

推荐答案

工作示例: http://jsfiddle.net/Gajotres/K69AJ/

这个例子是用jQuery Mobile事件制作的,所以它只适用于jQuery Mobile。在Windows和Android平台上测试。

This example is made with jQuery Mobile events so it will only work with jQuery Mobile. Tested on Windows and Android platform.

Vmouse事件用于弥合桌面和移动浏览器之间的差异。

Vmouse events are made to bridge the difference between desktop and mobile browsers.

另请注意以下一行:

event.preventDefault();

Android平台需要它,平台有一个讨厌的触摸移动检测错误。错误报告: http://code.google.com/p/android/问题/细节?id = 19827

It is needed for Android platform, platform has a nasty bug with touch movement detection. Bug report: 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){}
}

这篇关于如何通过jQuery Mobiles滑动事件获得方向和距离的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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