轻量高效的拓扑图组件
zh

Safari Mobile中的事件处理 - touch, gesture, mouse events

2013-07-22

Safari for Mobile中使用触控操作,传统的鼠标事件无法完全支持,比如没有mousemove, dblclick事件,要想灵活处理交互,可以通过监听TouchEvent和GestureEvent,下面是各个事件调用顺序的介绍:

保留的mouse事件

safari mobile中也保留有部分鼠标事件,如:mousedown/mouseup/mouseover/moouseout/mouseclick, 当然这些事件本身还是由touch事件开始触发的,准确的说只在单点触摸时触发,且在touch事件之后。

四种touch事件

touchstart, touchmove, touchend, touchcancel,分别表示触摸,移动,抬起手指,取消(我还不知道什么时候会调到这里)

三种gesture事件

如果有多点触摸,每个点都会派发自己的touch事件,当然处理一堆touch事件会比较麻烦,safari同时会派发gesture事件,包括gesturestart, gesturechange, gestureend, 分别表示开始多点触摸,触点在移动,结束多点触摸,IPhone中双指捏拉伸过程中都会派发这些事件。

单点触摸过程

多点触摸属于高级事件,我暂时用不到,只对单点的情况作处理。

判断是否是单点触摸:

[javascript]evt.touches.length == 1[/javascript] 几种常见操作

点击 - tap

touchstart, touchend, (mouseout, mouseover,) mousedown, mouseup, click

点击移动 - tap and move

touchstart, touchmove, touchend

连续两次触摸 - double tap

touchstart, touchend, touchstart, touchend

多点触摸 - pinch

(touchstart, )gesturestart, touchstart, gesturechange, touchmove, gesturechange, touchmove, gestureend, touchend 从上面的事件顺序可以看到,只有在轻拍动作时会触发mouse 事件,其他情况下都不会触发(包括双击,两只手指同时点击……)

扩展事件

有很多种触摸操作方式,如双击(double tap),长按(touch and hold),捏(pinch)…没有直接这样类型的事件,比如safari mobile中并没有doubletap事件可以监听,也没有hold事件,只有上面列的四种touch,三种gesture,而像双击这样的比较常用,可以自己扩展, 如double tap:

双击时间的定制

[javascript] svg.ontouchstart = function(evt){ if(evt.touches.length == 1){ var now = evt.timeStamp; if(this.touchTime && now - this.touchTime < 200){//时间间隔200ms时算 double tap delete this.touchTime; this.doubletap(evt, this); //这里判断是double tap } this.touchTime = now; } }; [/javascript] 同样touchhold也有办法,可以通过timer实现,复杂一下,这里不作细究

获取触点位置和target

touch 事件也有target属性,可以如桌面版的mouse事件同样处理 对于位置需要注意,因为touch事件包含多个触点的信息,也就是说包含多个触点的位置,对于单点触摸的情况,也要取touch集合中的第一个 [javascript]var touch = evt.touches[0];//取第一个触点 var x = touch.clientX; var y = touch.clientY;[/javascript] 备注:没有touch.layerX属性,用clientX代替,这可能与mobile上的缩放布局机制不同有关,待后研究

Next Prev