vue3中使用element-plus的el-scrollbar实现自动滚动(横向/纵横滚动)

vue3中使用element-plus的el-scrollbar实现自动滚动(横向/纵横滚动)

一、实现效果

el-scrollbar自动滚动

二、实现方式
cpp 复制代码
<div class="h-full overflow-y-auto overflow-x-hidden">
	<el-scrollbar height="100%" ref="scrollRef" v-loading="isLoading" element-loading-background="transparent">
		<!-- 滚动的内容 根据需求补充-->
		<div class="grid grid-cols-2 auto-cols-fr gap-4" style="grid-auto-flow: row; height: max-content">
					
		</div>
	</el-scrollbar>
</div>
cpp 复制代码
/* 设置滚动功能 */
	const scrollRef = ref<any>(null) // 滚动条引用
	let outerTimer: any = null
	const OUTER_SCROLL_SPEED = 1 // 外部滚动速度

	// 启动外部滚动
	const startOuterScroll = () => {
		if (outerTimer) {
			clearInterval(outerTimer)
		}
		outerTimer = setInterval(() => {
			if (!scrollRef.value) return

			const container = scrollRef.value.$el?.querySelector?.('.el-scrollbar__wrap')
			if (!container) return

			// 判断是否已滚动到底部
			if (container.scrollHeight - (container.scrollTop + container.clientHeight) <= 1) {
				// 滚动到顶部
				container.scrollTop = 0
			} else {
				// 向下滚动
				container.scrollTop += OUTER_SCROLL_SPEED
			}
			//纵向滚动如下:
			// // 确保内容宽度大于容器宽度才滚动
			// if (container.scrollWidth > container.clientWidth) {
			// 	// 判断是否已滚动到最右边
			// 	if (container.scrollWidth - (container.scrollLeft + container.clientWidth) <= 1) {
			// 		// 滚动到最左边
			// 		container.scrollLeft = 0
			// 	} else {
			// 		// 向右滚动
			// 		container.scrollLeft += INNER_SCROLL_SPEED
			// 	}
			// }
		}, 50)
	}
	
	// 停止外部滚动
	const stopOuterScroll = () => {
		if (outerTimer) {
			clearInterval(outerTimer)
			outerTimer = null
		}
	}

	// 启动所有滚动
	const startAllScroll = () => {
		startOuterScroll()
	}

	// 停止所有滚动
	const stopAllScroll = () => {
		stopOuterScroll()
	}

	// 鼠标进入处理
	const handleMouseEnter = () => {
		stopAllScroll()
	}

	// 鼠标离开处理
	const handleMouseLeave = () => {
		startAllScroll()
	}

	onMounted(() => {
		// 延迟启动滚动,确保DOM已渲染
		setTimeout(() => {
			startAllScroll()
		}, 500)
	})

	onUnmounted(() => {
		stopAllScroll()
	})
相关推荐
moshuying1 小时前
网购能买Token了!
前端
h_65432101 小时前
echarts实现柱状图加一条横线
前端·echarts
风骏时光牛马1 小时前
生成一个后端标题,只需要一个标题,不需要其他的任何文本。
前端
子非鱼@Itfuture1 小时前
关于前后端联调中登录状态/登录信息失效?
java·前端
郭小李1 小时前
openFeign入门
java·开发语言·前端
馒头不想说话1 小时前
AI当运营,帮你省人力
前端
梦曦i2 小时前
uni-app x下自研架构的工程化突围
前端·架构·uni-app x
速易达网络2 小时前
ECharts 图表制作完全指南:从零到可视化实战
前端·javascript·echarts
IT_陈寒2 小时前
SpringBoot多环境配置把我坑惨了,这个踩坑经验你最好看看
前端·人工智能·后端
徐小夕2 小时前
深度剖析 30k star 的编码 Agent DeepSeek-Reasonix:长会话 Token 成本直降 80%
前端·vue.js·github