我编写了一个代码,以像素为单位记录触摸移动的距离。
当我向左移动手指时,我在控制台中得到的是“0、-9、-10、-11、-12 等”。每次都在 0 和 -9 之间出现这种奇怪的差距。 为什么?代码并不复杂,一定有我不明白的地方。
这是我的代码:
let move = {'x':0, 'startX':0};
let body = $('body');
$(document).ready(function(){
//when touch starts, record initial position and the move distance of 0
body.on('touchstart', function (e){
//get finger X position
if(typeof e.clientX !== 'undefined'){
move.x = e.clientX;
} else {
move.x = e.originalEvent.touches[0].clientX;
}
//record initial position and move distance
move.startX = move.x;
move.x = move.x - move.startX;
//log
console.log(move.x);
});
//when touch move continues, calculate distance
body.on('touchmove', function (e){
//get finger X position
if(typeof e.clientX !== 'undefined'){
move.x = e.clientX;
} else {
move.x = e.originalEvent.touches[0].clientX;
}
//record move distance
move.x = move.x - move.startX;
//log
console.log(move.x);
});
//when touch ends, reset data
body.on('touchend', function (){
some = {'x':0, 'startX':0};
});
});
更新。 这似乎有效:
function reset(){return{'x':0, 'startX':null};}
let some = reset();
$(document).ready(function(){
body.on('touchmove', function (e){
let pos = typeof e.clientX !== 'undefined' ? some.x = e.clientX : e.originalEvent.touches[0].clientX;
some.startX = some.startX !== null ? some.startX : pos;
some.x = pos - some.startX;
console.log(some);
});
body.on('touchend', function (){some = reset();});
});