移动端笔记——jQuery touch事件

判断移动端还是pc端
function IsPC()  
{  
           var userAgentInfo = navigator.userAgent;  
           var Agents = new Array("Android", "iPhone", "SymbianOS", "Windows Phone", "iPad", "iPod");  
           var flag = true;  
           for (var v = 0; v < Agents.length; v++) {  
               if (userAgentInfo.indexOf(Agents[v]) > 0) { flag = false; break; }  
           }  
           return flag;  
}         
        $(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上,则使用鼠标事件,在移动设备中,就使用触摸事件,就这么简单。

出处:http://blog.csdn.net/jiangcs520/article/details/17564065