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()
	})
相关推荐
一只小bit12 小时前
Qt 多媒体:快速解决音视频播放问题
前端·c++·qt·音视频·cpp·页面
梦65012 小时前
React 高阶组件
前端·react.js·前端框架
CHU72903512 小时前
智慧回收新体验:同城废品回收小程序的便捷功能探索
java·前端·人工智能·小程序·php
Marshmallowc12 小时前
从URL变化到组件重绘:React Router 状态分发机制与组件挂载逻辑深度全解
前端·react.js·前端框架·react router·组件生命周期
摘星编程13 小时前
在OpenHarmony上用React Native:MapView路线规划
javascript·react native·react.js
徐小夕@趣谈前端13 小时前
【推荐】jitword协同文档新增AI公文助手,一键生成红头文件
vue.js·人工智能·开源·编辑器·github
虹少侠13 小时前
基于 WebKit 构建 macOS 多浮窗视频播放的技术实践(含完整产品落地)
前端·macos·swift·webkit
木易 士心13 小时前
Vue 响应式数据失效全解析:从原理机制到工程实践
前端·javascript·vue.js
Rattenking13 小时前
【CSS】---- 根据【张鑫旭-高宽不等图片固定比例布局的三重进化】的思考
前端·css
AC赳赳老秦13 小时前
ELK栈联动:DeepSeek编写Logstash过滤规则与ES日志分析逻辑
运维·前端·javascript·低代码·jenkins·数据库架构·deepseek