1. 程式人生 > >獲取touchstart,touchmove,touchend 坐標

獲取touchstart,touchmove,touchend 坐標

doc chm jquer gin cti pagex touch 需要 func

簡單說下如何用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)
{
  //...
}

獲取touchstart,touchmove,touchend 坐標