获取touchstart,touchmove,touchend 坐标

简单说下如何用jQuery 和 js原生代码获取touchstart,touchmove,touchend 坐标值:

jQuery 代码:

$('#id').on('touchstart',function(e) {
    var _touch = e.originalEvent.targetTouches[0];
    var _x= _touch.pageX;
});
 
$('#id').on('touchmove',function(e) {
    var _touch = e.originalEvent.targetTouches[0];
    var _x= _touch.pageX;
});
 
$('#id').on('touchend',function(e) {
    var _touch = e.originalEvent.changedTouches[0];
    var _x= _touch.pageX;
}

 

js原生代码

document.getElementById("id").addEventListener("touchstart",function(e)
{
    var _x=e.touches[0].pageX;
    var _y=e.touches[0].pageY;
    console.log("start",_x)
})
document.getElementById("id").addEventListener("touchmove",function(e)
{
    var _x=e.touches[0].pageX;
    var _y=e.touches[0].pageY;
    console.log("move",_x)
})
document.getElementById("id").addEventListener("touchend",function(e)
{
    var _x=e.changedTouches[0].pageX;
    var _y=e.changedTouches[0].pageY;
    console.log("end",_x)
})

 

以上两种办法中 touchend 需要使用changedTouches[0]。

一般我们取第一个手指的坐标,如果有其他要求,可能需要判断手指数量。

if (e.targetTouches.length == 1)
{
  //...
}

 

posted @ 2017-08-08 20:14  前端[色色]  阅读(5382)  评论(0编辑  收藏  举报