拖拽 / 滑动事件中所存在的问题
前端开发中有许许多多的拖拽与手机滑动的行为,大多数UI库都封装了很多这类事件,但这样却有个问题。就是当我们需要根据自身情况逻辑来定义这类事件时却会有很大局限性,原生代码实现又十分繁琐复制,且难以管理。
resusable-drag库的实现观念
意识到这个问题后我开发了一个实现可复用拖拽/滑动的功能库,语法架构参考Vue的数据管理结构,该库实现的观念是可以高度自定义实现这类事件,并有很好的扩展性与简便性。
github地址: https://github.com/TuiMao233/...
npm地址: https://www.npmjs.com/package...
该库的使用步骤如下。
引入库
import reusableDrag from 'resusable-drag'
<!-- 又或者script中引入 -->
<script src="./js/resusable-drag.js"></script>
定义一个滑动/拖拽封装
const touch_sliding_screen = new reusableDrag({
data() {
return {
// 自定义默认使用的数据,滑动延迟,或者其他数据等
// 在这里定义的数据可在后续逻辑中使用
wrapper: this.el.querySelector('.wrapper'),
pagination: this.el.querySelector('.pagination'),
slidingDistance: 300,
delay: 2000,
//.....
}
},
mounted() {
// 定义初始化执行
this.el.style.background = 'rgba(0,0,0,.5)'
//....
},
methods: {
// 定义行为方法
setWidth :function () {
//....
}
},
// resusable-drag 会检测当前设备类型, 当检测到是移动设备时, 自动切换为touch等事件
touch: {
// 定义滑屏事件行为
start: function (ev) {
},
move: function (ev) {
},
end: function (ev) {
}
},
// resusable-drag 会检测当前设备类型, 当检测到是PC设备时, 自动切换为mouse等事件
/* mouse: {
// 或定义PC端拖拽事件行为
down (ev) {},move (ev) {},up (ev) {}
}, */
})
创建一个拖拽/滑动
在创建一个拖拽时,可以传入自定义数据,该数据会覆盖掉data中的数据,并且会在事件逻辑中使用覆盖数据。
touch_sliding_screen.create({
el:document.querySelector('.mi-carousel'),
slidingDistance: 300,
delay: 1000,
// mouseclasp:{down(r){},move(r){},up(r){}}, // mouseclasp
// touchclasp:{start(r){},move(r){},end(r){}} // touchclasp
})
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。