问题描述:
js的触屏事件,主要有三个事件:touchstart,touchmove,touchend。
这三个事件最重要的属性是 pageX和 pageY,表示X坐标,Y坐标。
touchstart=在触摸开始时触发事件
touchend=在触摸结束时触发事件
touchmove=这个事件比较奇怪,按道理在触摸到过程中不断激发这个事件才对,但是在我的 Android 中,在 touchstart 激发后激发一次,然后剩余的都和 touchend 差不多同时激发。
这三个事件都都有一个 timeStamp 的属性,查看 timeStamp 属性,可以看到顺序是 touchstart -> touchmove ->touchmove -> … -> touchmove ->touchend
第一种方案:
在监听touchstart或者touchmove事件的函数里,阻止事件的默认行为event.preventDefault(),那么到touchend就能正常触发
<div class="btn" @touchstart="touchstart" @touchend="touchend"></div>
touchend(event) {
//松开按键
event.preventDefault();
}
第二种方案:
同时绑定touchcancel和touchend事件,这样在安卓上就能通过触发touchcancel来重新展示我们的按钮。
<div class="btn" @touchstart="touchstart" @touchend="touchend" @touchend="touchcancel"></div>
touchend(event) {
//松开按键
}
第三种方案:
阻止任何父事件的 event.stopPropagation()行为,那么到touchend就能正常触发。
<div class="btn" @touchstart="touchstart" @touchend="touchend"></div>
touchend(event) {
//松开按键
//阻止任何父事件处理程序被执行
event.stopPropagation();
}
第四种方案:
问题:
如果触发了 touchmove, touchend 就不会被触发了, 而且 touchmove 没有持续触发。
解决方法:
只要在 touchstart 的时候调用下 event.preventDefault(); 即可让其他事件都正常被触发了。
$(document).on("touchstart",".btn-highlight",function(){
$(this).addClass("hover");
}).on("touchmove",".btn-highlight",function(event){
event.preventDefault();
}).on("touchcancel touchend",".btn-highlight",function(event){
$(this).removeClass("hover");
});