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



966

被折叠的 条评论
为什么被折叠?



