zepto触摸事件解决方法

移动项目开发过程中,经常需要用到滑动的事件来处理一些效果。通常情况下,我们会通过  touchstart->touchmove->touchend  的过程来定义这个事件。这些事件的触发顺序是  touchstart, touchmove, touchmove ….. touchend  。绝大部分平板或手机也正如我们想象的那样有序执行着。但是以Android 4.0.4为首的一些可恶分子却有些不听话:他们的touchend事件没有如预期的那样触发。

监听这些事件我们会发现,当只是轻点一下屏幕时,touchend可以正常触发。但是只要当 touchmove 被触发之后,touchend 就不会再被触发了,而且 touchmove 也没有持续触发。

在网上搜集了一些资料显示,这是 Android 上浏览器的bug

> On Android ICS if no preventDefault is called on touchstart or the firsttouchmove,
> further touchmove events and the touchend will not be fired.

正如提到的我们只需要在 touchstart 或者 touchmove 里执行一下 e.preventDefault(); 就可以避免这个bug。但是,问题来了:添加了 preventDefault 之后,正常的scroll事件也被屏蔽了!我们意外的发现滚动条也不能用了!

于是,我们开始尝试各种添加preventDefault事件的时机:闭包,延迟,判断等一一用上。最终焦点落在了firsttouchmove上,于是有了以下代码。

var touchY = 0;
$(this).on('touchstart', function(e){
    var touch = e.touches[0];
    touchY = touch.clientY;
}).on('touchmove', function(e){
    var touch = e.touches[0]
    if(Math.abs(touch.clientY - touchY) < 10){
        e.preventDefault();
    }
}).on('touchend', function(){
    // 你的滑动事件
});

基本上主要的思想就是在 touchmove 的时候判断出纵轴的位移量,当小于某个值的时候就认为是在执行左右滑动,且需要执行 preventDefault 来确保 touchend 可以正常触发。当然,如果你有横向滚动条且想绑定上下滑动事件的话就需要自己修改一下代码。

参考:

http://blog.mobiscroll.com/working-with-touch-events/.

 

posted @ 2016-03-18 11:05  没事看看电影  阅读(3203)  评论(0编辑  收藏  举报