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()
	})
相关推荐
kyriewen20 分钟前
我把今年流传的前端 AI 面试题整理了一遍——4 类场景题+回答框架(附速查表)
前端·面试·程序员
计算机魔术师1 小时前
国产多模态模型正面硬刚Opus旗舰:差距从30%缩到3%
前端
风骏时光牛马1 小时前
程序员进阶:深度思考,解锁职场成长的底层逻辑
前端
IT_陈寒1 小时前
用了Proxy才发现以前的JavaScript白写了
前端·人工智能·后端
爱丶不疚2 小时前
Eval: Agent 说的 Eval 是什么?从单测、TDD 到 Sentry 聊起
前端·ai编程·vibecoding
求道於盲2 小时前
python中的类型标注
前端
计算机魔术师2 小时前
从硅谷测试到全球铺开,ChatGPT广告的10亿美元秘密
前端
专业抄代码选手3 小时前
08|Fiber 上的 `useState`:状态终于属于具体组件
前端·javascript·react.js
默_笙3 小时前
😭 Vibe Coding 翻车实录:AI 编程为什么必须先写"剧本"
前端·javascript
LEE3 小时前
原来 Claude Code 最厉害的工具,一行代码都不写
前端·后端