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()
	})
相关推荐
独泪了无痕21 小时前
使用Fetch API 探索前后端数据交互
前端·http·交互设计
css趣多多21 小时前
别名路径的知识点
前端
靓仔建1 天前
Vue3导入组件出错does not provide an export named ‘user_setting‘ (at index.vue:180:10)
开发语言·前端·typescript
EnoYao1 天前
我写了一个团队体检报告 Skill,把摸鱼的同事扒出来了😅
前端·javascript
梁正雄1 天前
Python前端-2-css练习
前端·css·python
清汤饺子1 天前
用 Cursor 半年了,效率还是没提升?是因为你没用对这 7 个功能
前端·后端·cursor
Never_Satisfied1 天前
在JavaScript / Node.js中,package.json文件中的依赖项自动选择最新版安装
javascript·node.js·json
蓝莓味的口香糖1 天前
【vue3】组件的批量全局注册
前端·javascript·vue.js
wefly20171 天前
开发者效率神器!jsontop.cn一站式工具集,覆盖开发全流程高频需求
前端·后端·python·django·flask·前端开发工具·后端开发工具
独泪了无痕1 天前
自动导入 AutoImport:告别手动引入依赖,优化Vue3开发体验
前端·vue.js·typescript