移动端touchstart,touchmove,touchend

近段时间使用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也很方便,就不做多解释了。

demo

var praiseBtn=document.querySelector('.praiseBtn');//获取div
        praiseBtn.addEventListener("touchstart",StartPraiseBtn,false);//添加触摸事件
        praiseBtn.addEventListener("touchend",StopPraiseBtn,false);//添加触摸事件
        //touchstart
        function StartPraiseBtn()
        {
            document.querySelector('.praiseBtn').className="praiseBtn current";//添加open类
        }
        //touchend
        function StopPraiseBtn()
        {
            document.querySelector('.praiseBtn').className="praiseBtn current";
        }

  

原文地址:https://www.cnblogs.com/hellman/p/5282968.html