在vue3 中,使用element-plus中的el-scrollbar,让内容元素自动滚动

最近在项目中遇到一个要求,希望在工程简介中文字能自动循环滚动,鼠标移入停止滚动,移出又继续滚动,接下来我们来实现:

一、html部分

<div class="pubilc">
    <pubilc-title title="工程简介"></pubilc-title>
    <div class="pubilc-content">
	<div class="l-c-c">
	    <el-scrollbar ref="scrollRef" height="170px" class="scroll-container" @mouseenter="stopScroll" @mouseleave="startScroll">
	        <p>
		{{ info.description }}
		</p>
            </el-scrollbar>
	 </div>
    </div>
</div>

二、js部分

/* 设置 el-scrollbar 自动滚动 */
const scrollRef = ref<any>(null)
let timer: any = null
const SCROLL_SPEED = 1 // 每次滚动的像素数,可以根据需要调整

const startScroll = () => {
	if (timer) {
		clearInterval(timer)
	}
	timer = setInterval(() => {
		// 获取滚动容器
		const container = scrollRef.value.$el.querySelector('.el-scrollbar__wrap')
		// 判断是否已滚动到底部
		if (container.scrollHeight - (container.scrollTop + container.clientHeight) <= 1) {
			// 滚动到顶部
			container.scrollTop = 0
		} else {
			// 向下滚动
			container.scrollTop += SCROLL_SPEED
		}
	}, 30) // 根据需要调整滚动间隔
}

const stopScroll = () => {
	if (timer) {
		clearInterval(timer)
	}
}

onUnmounted(() => {
	stopScroll()
})

onMounted(() => {
	startScroll()
})

三、css部分

.l-c-c {
	width: 100%;
	height: 180px;
	overflow-y: auto;

	p {
		font-size: 16px;
		letter-spacing: 2px;
		line-height: 34px;
	}
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值