any-touch

演示
目录
安装
npm i -S any-touchCDN
https://unpkg.com/any-touch/dist/any-touch.umd.min.js
快速开始
HTML中引入
<h1 id="box">hello world</h1>
<script src="https://unpkg.com/any-touch/dist/any-touch.umd.min.js"></script>
<script>
const el = doucument.getElementById('box');
const at = new AnyTouch(el);
at.on('tap', e => console.log('e包含位置等信息',e));
</script>或者, 使用NPM
import AnyTouch from 'any-touch';
const el = doucument.getElementById('box');
const at = new AnyTouch(el);
at.on('pan', e => console.log('e包含位移/速度/方向等信息',e))兼容vue语法
<div
@tap="onTap"
@swipe="onSwipe"
@press="onPress"
@pan="onPan"
@pinch="onPinch"
@rotate="onRotate">
<p>Hello any-touch</p>
</div>import AnyTouch from 'any-touch';
export default {
mounted() {
// 没错, 就这2行
const at= new AnyTouch(this.$el);
this.on('hook:destroyed', ()=>{at.destroy()});
}
};<!-- 有效 -->
<div @tap="onTap"></div>
<!-- 不生效, 监听不到tap -->
<my-component @tap="onTap"></my-component>支持微信小程序
由于小程序中没有dom元素的概念, 所以我们需要通过catchEvent方法手动接收touch事件的事件对象来进行识别!
<view
@touchstart="at.catchEvent"
@touchmove="at.catchEvent"
@touchend="at.catchEvent"
@touchcancel="at.catchEvent">
</view>const at = new AnyTouch()
{
onload(){
at.on('press', onPress);
}
}按需加载
默认any-touch支持所有手势, 为了更小的体积, 提供了按需加载.
// 只加载pan识别器(拖拽)
import Core from '@any-touch/core';
import Pan from '@any-touch/pan';
// 使用Pan
const at = Core(el);
at.use(Pan);
// 拖拽
at.on('swipe', onSwipe);npm i any-touch后, "@any-touch/core"和"@any-touch/xx手势"便已自动安装, 直接引入即可.
@any-touch/core
手势库的核心组件, 主要用来实现PC/移动端的兼容(查看更多).
@any-touch/xx手势
手势识别器均已做成独立的包, 从而实现按需加载.
| 名称 | 说明 |
|---|---|
| @any-touch/tap | 点击 |
| @any-touch/pan | 拖拽 |
| @any-touch/swipe | 划 |
| @any-touch/press | 按压 |
| @any-touch/pinch | 缩放 |
| @any-touch/rotate | 旋转 |
注意事项
手势识别器的name字段必填
自定义手势一定记得给起一个名字哦, 而且不要和默认存在的手势同名(已有tap/swipe/pan/rotate/pinch/press).
at.use(Tap, { pointLength: 2 , name:'twoFingersTap'});
at.on('twoFingersTap', onTwoFingersTap);不要用 alert 调试
touchstart或touchmove阶段触发了alert, 会出现后续的touchmove/touchend不触发的 bug. 所以请大家务必避免在手势的事件回调中使用alert.
测试代码
如果仅仅是了在移动端调试, 请使用腾讯的vconsole
macos上的chrome浏览器触发touchend会比较慢
由于上述原因, swipe事件发生的会"慢半拍",所以请大家最终测试以手机效果为准.