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()
	})
相关推荐
xiaotao1312 小时前
第九章:Vite API 参考手册
前端·vite·前端打包
午安~婉2 小时前
Electron桌面应用聊天(续)
前端·javascript·electron
彧翎Pro2 小时前
基于 RO1 noetic 配置 robosense Helios 32(速腾) & xsense mti 300
前端·jvm
小码哥_常2 小时前
解锁系统设置新姿势:Activity嵌入全解析
前端
之歆3 小时前
前端存储方案对比:Cookie-Session-LocalStorage-IndexedDB
前端
哟哟耶耶3 小时前
vue3-单文件组件css功能(:deep,:slotted,:global,useCssModule,v-bind)
前端·javascript·css
是罐装可乐3 小时前
深入理解“句柄(Handle)“:从浏览器安全到文件系统访问
前端·javascript·安全
华科易迅3 小时前
Vue如何集成封装Axios
前端·javascript·vue.js
康一夏3 小时前
Next.js 13变化有多大?
前端·react·nextjs
糖炒栗子03263 小时前
前端项目标准环境搭建与启动
前端