移动设备手势事件库Touch.js使用详解

作者:流萤

时间:2026-10-22

浏览:546

本文详细介绍Touch.js手势库在Webkit内核移动设备中的应用。涵盖旋转、缩放、点击、滑动、拖拽及原生触摸事件的具体实现方法,通过代码示例解析API使用,帮助开发者快速掌握移动端交互开发。

文章目录

Touch.js库概述

Touch.js是一款专为Webkit内核移动浏览器设计的手势识别与事件处理库。该库基于原生事件构建,支持事件代理机制,从而提供更优的性能表现。其API设计极简,便于开发者快速上手使用。

旋转事件处理

1、旋转事件- startRotate


var angle = 0;
touch.on('#target', 'touchstart', function(ev){
ev.startRotate();
ev.preventDefault();
});
touch.on('#target', 'rotate', function(ev){
var totalAngle = angle + ev.rotation;
if(ev.fingerStatus === 'end'){
angle = angle + ev.rotation;
}
this.style.webkitTransform = 'rotate(' + totalAngle + 'deg)';
});

双指缩放功能实现

2、双指缩放事件-Scale


var target = document.getElementById("target");
target.style.webkitTransition = 'all ease 0.05s';
touch.on('#target', 'touchstart', function(ev){
ev.preventDefault();
});
var initialScale = 1;
var currentScale;
touch.on('#target', 'pinchend', function(ev){
currentScale = ev.scale - 1;
currentScale = initialScale + currentScale;
currentScale = currentScale > 2 ? 2 : currentScale;
currentScale = currentScale < 1 ? 1 : currentScale;
this.style.webkitTransform = 'scale(' + currentScale + ')';
log("当前缩放比例为:" + currentScale + ".");
});
touch.on('#target', 'pinchend', function(ev){
initialScale = currentScale;
});

点击与长按手势识别

3、识别单击, 双击和长按事件-Tap & Hold


touch.on('#target', 'hold tap doubletap', function(ev){
//console.log(ev.type);
});

左右滑动事件处理

4、向左, 向右滑动-Swipe


touch.on('#target', 'touchstart', function(ev){
ev.preventDefault();
});
var target = document.getElementById("target");
target.style.webkitTransition = 'all ease 0.2s';
touch.on(target, 'swiperight', function(ev){
this.style.webkitTransform = "translate3d(" + rt + "px,0,0)";
log("向右滑动.");
});
touch.on(target, 'swipeleft', function(ev){
log("向左滑动.");
this.style.webkitTransform = "translate3d(-" + this.offsetLeft + "px,0,0)";
});

拖拽交互实现

5、拖拽事件-Drag


touch.on('#target', 'touchstart', function(ev){
ev.preventDefault();
});
var target = document.getElementById("target");
var dx, dy;
touch.on('#target', 'drag', function(ev){
dx = dx || 0;
dy = dy || 0;
log("当前x值为:" + dx + ", 当前y值为:" + dy +".");
var offx = dx + ev.x + "px";
var offy = dy + ev.y + "px";
this.style.webkitTransform = "translate3d(" + offx + "," + offy + ",0)";
});
touch.on('#target', 'dragend', function(ev){
dx += ev.x;
dy += ev.y;
});

原生触摸事件监听

6、原生事件-Touch


touch.on('#target', 'touchstart touchmove touchend', function(ev){
console.log(ev.type);
});

touch.js官方网站:http://touch.code.baidu.com/

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持本站。

实用工具推荐

电子包浆

绿化、压缩、噪点和虚拟水印,自由调节做旧程度。

使用 ›
图片压缩

选择画质和输出格式,预览压缩前后的大小。

使用 ›
相关文章