js Touch事件(向左滑动,后退)

时间:2021-12-03 17:10:56

js Touch事件(向左滑动,后退)

代码如下

var touch_p = {
c_x : 0,
c_y : 0,
hasbacked : false
};
function touches(ev){
if(ev.touches.length==1){
switch(ev.type){
case 'touchstart':
if(console)
console.log('Touch start('+ev.touches[0].clientX+', '+ev.touches[0].clientY+')');
touch_p.c_x = ev.touches[0].clientX;
touch_p.c_y = ev.touches[0].clientY;
ev.preventDefault();
break;
case 'touchend'://未成功触发,未找到原因
//oDiv.innerHTML='Touch end('+ev.changedTouches[0].clientX+', '+ev.changedTouches[0].clientY+')';
if(console)
console.log('Touch end('+ev.changedTouches[0].clientX+', '+ev.changedTouches[0].clientY+')');
break;
case 'touchmove':
var tempX = ev.changedTouches[0].clientX;
var tempY = ev.changedTouches[0].clientY;
var diff_x = tempX - touch_p.c_x;
var diff_y = Math.abs(tempY - touch_p.c_y);
/*console.log('Touch move('+ev.changedTouches[0].clientX+', '+ev.changedTouches[0].clientY+')<br>diff_x=' + diff_x
+ "<br>diff_y=" + diff_y);*/
//x轴方向移动超过150 纵轴方向移动小于30
if(!touch_p.hasbacked && diff_x > 150 && diff_y < 30){
goback();
}
break; }
}
}
document.addEventListener('touchstart',touches,false);
document.addEventListener('touchend',touches,false);
document.addEventListener('touchmove',touches,false);
function goback() {
if(console)
console.log("go back");
touch_p.hasbacked = true;
window.history.back();
}