zoukankan      html  css  js  c++  java
  • 移动端touchstart,touchmove,touchend

    转载:http://www.cnblogs.com/hellman/p/5282968.html

    近段时间使用html5开发一个公司内部应用,而触摸事件必然是移动应用中所必须的,刚开始以为移动设备上或许也会支持鼠标事件,原来是不支持的,好在webkit内核的移动浏览器支持touch事件,并且打包成app也毫无压力。原本以为touch事件应该跟鼠标事件是一样的道理,实践过程中虽然不难,但还是碰到了不少坑,才发现还是略有区别的。

    $(document).bind(touchEvents.touchstart, function (event) {
                event.preventDefault();
                
            });
            $(document).bind(touchEvents.touchmove, function (event) {
                event.preventDefault();
                
            });
    
            $(document).bind(touchEvents.touchend, function (event) {
                event.preventDefault();
                
            });

    很多博文中称touch的三个事件都有targetTouches,touches以及changedTouches对象列表,其实不然,touchend事件中应该是只有个changedTouches触摸实例列表的,而且这里说明一下,回调函数的event只是一个普通的object对象,实际上event中有一个originalEvent属性,这才是真正的touch事件,这个事件中才存在着上诉三个触摸实例列表,这三个实例存储了触摸事件的位置等等属性,类似于鼠标事件。其他地方基本与鼠标事件是一致的。简单介绍一下这三个触摸列表,touches是在屏幕上的所有手指列表,targetTouches是当前DOM上的手指列表,所以当手指移开触发touchend事件时,event.originalEvent是没有这个targetTouches列表的,而changedTouches列表是涉及当前事件的列表,例如touchend事件中,手指移开。接下来谈谈pc与移动端的适配问题,既然使用html5,当然是看中他的跨平台特性了,不仅仅要ios和android适配,pc上直接打开网页最好也是可以的,但是pc上只支持鼠标事件怎么办。好办,仔细观察上面代码的触摸事件,touchEvents.touchXXX,看如下代码:

    var touchEvents = {
            touchstart: "touchstart",
            touchmove: "touchmove",
            touchend: "touchend",
    
            /**
             * @desc:判断是否pc设备,若是pc,需要更改touch事件为鼠标事件,否则默认触摸事件
             */
            initTouchEvents: function () {
                if (isPC()) {
                    this.touchstart = "mousedown";
                    this.touchmove = "mousemove";
                    this.touchend = "mouseup";
                }
            }
        };


    若在pc上,则使用鼠标事件,在移动设备中,就使用触摸事件,就这么简单,判断是否pc也很方便,就不做多解释了。

     1 var praiseBtn=document.querySelector('.praiseBtn');//获取div
     2         praiseBtn.addEventListener("touchstart",StartPraiseBtn,false);//添加触摸事件
     3         praiseBtn.addEventListener("touchend",StopPraiseBtn,false);//添加触摸事件
     4         //touchstart
     5         function StartPraiseBtn()
     6         {
     7             document.querySelector('.praiseBtn').className="praiseBtn current";//添加open类
     8         }
     9         //touchend
    10         function StopPraiseBtn()
    11         {
    12             document.querySelector('.praiseBtn').className="praiseBtn current";
  • 相关阅读:
    Entity Framework后台采用分页方式取数据与AspNetPager控件的使用
    Excel Interactive View
    让Visual Studio 2013为你自动生成XML反序列化的类
    如何在C#中生成与PHP一样的MD5 Hash Code
    JavaScript text highlighting JQuery plugin
    JQuery文本框水印插件的简单实现
    Chrome浏览器在Windows8/8.1下显示模糊的解决办法
    Sharing count on Facebook, Twitter, and LinkedIn
    Windows 8.1——将网站固定到开始菜单,自定义图标、颜色和Windows推送通知
    [转]php使用 memcache 来存储 session
  • 原文地址:https://www.cnblogs.com/zhaobao1830/p/7243578.html
Copyright © 2011-2022 走看看