npm i -S any-touch
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 = document.getElementById('box');
const at = new AnyTouch(el);
at.on('tap', e => console.log('e包含位置等信息',e));
</script>
或者, 使用NPM
import AnyTouch from 'any-touch';
const el = document.getElementById('box');
const at = new AnyTouch(el);
at.on('pan', e => console.log('e包含位移/速度/方向等信息',e))
<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手势"便已自动安装, 直接引入即可.
手势库的核心组件, 主要用来实现PC/移动端的兼容(查看更多).
手势识别器均已做成独立的包, 从而实现按需加载.
名称 | 说明 |
---|---|
@any-touch/tap | 点击 |
@any-touch/pan | 拖拽 |
@any-touch/swipe | 划 |
@any-touch/press | 按压 |
@any-touch/pinch | 缩放 |
@any-touch/rotate | 旋转 |
除了上面说的6大类手势外, 还细分了更多手势:
手势名 | 说明 |
---|---|
pressup | 按压松开 |
panstart | 拖拽开始 |
panmove | 拖拽中 |
panend | 拖拽结束 |
pinchstart | 缩放开始 |
pinchmove | 缩放中 |
pinchend | 缩放结束 |
rotatestart | 旋转开始 |
rotatemove | 旋转中 |
rotateend | 旋转结束 |
at.on('panstart', e=>{
console.log('拖拽开始了!');
});
自定义手势一定记得给起一个名字哦, 而且不要和默认存在的手势同名(已有tap/swipe/pan/rotate/pinch/press).
at.use(Tap, { pointLength: 2 , name:'twoFingersTap'});
at.on('twoFingersTap', onTwoFingersTap);
❗❗❗ 在安卓手机的真机上, 如果touchstart
或touchmove
阶段触发了alert
, 会出现后续的touchmove/touchend
不触发的 bug. 所以请大家务必避免在手势的事件回调中使用alert
.
测试代码
如果仅仅是了在移动端调试, 请使用腾讯的vconsole
由于上述原因, swipe事件发生的会"慢半拍",所以请大家最终测试以手机效果为准.
在移动端touchstart比click先触发, 所以touchstart阶段的preventDefault会阻止click触发, 恰恰any-touch默认在touchstart中使用了preventDefault
, 用来阻止了浏览器默认事件的触发,比如click和页面滚动.
如果移动端非要使用click做如下设置
const at = new AnyTouch(el, { preventDefault: false });