zoukankan      html  css  js  c++  java
  • 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/.

  • 相关阅读:
    【JVM】模板解释器--如何根据字节码生成汇编码?
    你会swap吗,按值传递还是按引用?
    你了解实时计算吗?
    Hadoop的Server及其线程模型分析
    机会
    storm如何分配任务和负载均衡?
    storm基础框架分析
    storm如何保证at least once语义?
    学习笔记:The Log(我所读过的最好的一篇分布式技术文章)
    学习笔记:Twitter核心数据类库团队的Hadoop优化经验
  • 原文地址:https://www.cnblogs.com/hjsblogs/p/5291252.html
Copyright © 2011-2022 走看看