实现效果,拖动左右箭头实现图片区域同步滚动,到边缘停止拖动。
HTML代码
<template><div @touchstart="onClick"><!--使用draggable组件 图片列表区域--><draggablev-model="select_list"@end="onEnd"class="display_flex_ac list_all"id="imageAssignment"></draggable><!--自定义拖动条--><divref="container"class="scroll_bar"@touchend="endDrag"@touchcancel="endDrag"@touchstart="startDrag"@touchmove.prevent="drag"><divref="draggable"class="display_flex_ac_jc slide":style="{ transform: `translateX(${left}px)` }"><a-icon type="double-left" /><a-icon type="double-right" /></div></div></div>
</template>
JS代码
<script>
export default {data() {return {dragging: false,left: 0,startX: 0,currentX: 0,scrollWidth: 0,rollingValue: 0,containerWidth: 0,draggableWidth: 0,}},methods: {// 点击onClick(){this.containerWidth = this.$refs.container?.offsetWidth;this.draggableWidth = this.$refs.draggable?.offsetWidth;this.scrollWidth = document.getElementById("imageAssignment")?.scrollWidth;},// 拖动开始startDrag(e) {this.dragging = true;this.startX = e.touches[0].clientX - this.left;},// 拖动中drag(e) {if (this.dragging) {const minLeft = 0;const newX = e.touches[0].clientX - this.startX;const maxLeft = this.containerWidth - this.draggableWidth; // 去掉拖动元素宽度this.left = Math.max(minLeft, Math.min(maxLeft, newX)); // 当前拖动值const maxRight = this.scrollWidth - this.containerWidth; // 去掉当前屏幕this.rollingValue = this.onRolling(maxRight, maxLeft, this.left); // 计算滚动值document.getElementById("imageAssignment").scrollLeft = this.rollingValue;}},// 拖动结束endDrag() {this.dragging = false;},// 计算滚动条拖动值onRolling(maxRight, maxLeft, value) {// 计算比例关系const ratio = value / maxLeft;// 计算最终的值const finalValue = maxRight * ratio;// 返回最终值return finalValue;},// 拖动结束async onEnd(e) {// 同步滚动条位置let left = e.target.scrollLeft;const maxLeft = this.containerWidth - this.draggableWidth; // 去掉拖动元素宽度const maxRight = this.scrollWidth - this.containerWidth; // 去掉当前屏幕this.left = this.onRolling(maxLeft, maxRight, left); // 计算滚动条// 替换变化数据this.setImage_list(this.select_list);}}
}
</script>
CSS代码
.scroll_bar{width: 100%;overflow: auto;.slide{z-index: 1;height: 16px;bottom: -7px;opacity: 0.8;padding: 0 5px;position: absolute;border-radius: 5px;background: #fff;box-shadow: 0 0px 3px #999;.anticon{font-size: 12px;}}
}