原创内容,引用请注明原处
<template>
<div class="template-swiper-move">
<ul
ref="swiper"
class="swiper-list"
:style="{
transform: `translateX(${
moveX}px)`,
transitionDuration: `${
transDuration}ms`,
}"
@mousedown="handlerDragStart"
@mouseup="handlerMouseUp"
@touchstart="handlerTouchStart"
@touchmove="handlerTouchMove"
@touchend="handlerTouchEnd"
>
<slot></slot>
</ul>
</div>
</template>
模板使用的transform来滑动,注意:使用 transform 和 position 滑动不一样,获取到的dom数据会有不同,例如offsetLeft 在 transform下是无法获得的,同理position下可以获取到offsetLeft
1.事件处理
- pc端使用mousedown 和 mouseup
- 移动端使用touch的整个流程
2.使用变量
props: {
dataList: {
type: Array,
default: () => [],
},
},
data() {
return {
cellList: [], // 记录子集
moveX: 0, // 移动量
widthGap: 0, // 实际可滚动距离(左边界为0, widthGap为右边界)
oldMoveX: 0, // 上一次滑动的位置
oldx: 0, // 当前摁下的鼠标位置
transDuration: 0, // 设置动画时长
cellLeft: [], // 记录所有cell 的offsetLeft 值
}
},
3. 功能代码
handlerDragStart(event) {
const swiper = this.$refs.swiper
const scrollWidth = swiper.scrollWidth
this.widthGap = scrollWidth - this.$refs.swiper.clientWidth// 可滚动范围
this.oldMoveX = this.moveX // oldMoveX 是上一次滑动留下的距离
this.oldx = event.layerX
window.addEventListener('mousemove', this.handlerDragMove)
},
鼠标摁下,求得滚动范围,以及上一次滚动距离,当前鼠标摁下的距离,并且像window 添加鼠标滑动事件
handlerDragMove(event) {
const slideGap = event.layerX - this.oldx
this.moveX = this.oldMoveX + slideGap
},
鼠标滑动记录,当前滑动的距离,并且给偏移量moveX 赋值,
- 用鼠标滑动停止的距离layerX 减去 鼠标摁下时的即时位置, 获取鼠标实际滑动的距离,
- 实际滑动距离,加上上次移动的距离,等于最终滑动的偏移量
handlerMouseUp() {
window.removeEventListener('mousemove', this.handlerDragMove)
this.slideEnd()
},
// 滑动后结束处理
slideEnd() {
new Promise((resolve, reject) =>