vue3 element-plus el-scrollbar 自动滚动
一、实现效果
使用 el-scrollbar 实现自动滚动,鼠标移入则停止滚动,鼠标移出则继续滚动。
二、代码
AutoScroll.vue
注意:el-scrollbar 的外层容器需要设置高度,或者直接设置 .scroll-container 的高度。
<template>
<div class="content">
<el-scrollbar class="scroll-container" ref="scrollRef" @mouseenter="stopScroll" @mouseleave="startScroll">
<template v-for="(item, index) in warnList" :key="index">
<div class="warn-item">
<img src="https://fuss10.elemecdn.com/e/5d/4a731a90594a4af544c0c25941171jpeg.jpeg" alt="">
<div class="info">{{ item.number }}</div>
</div>
</template>
</el-scrollbar>
</div>
</template>
<script setup lang="ts">
import {onMounted, onUnmounted, ref} from "vue";
const warnList = ref<any[]>([
{
number: 1
},
{
number: 2
},
{
number: 3
},
{
number: 4
},
{
number: 5
}
])
/* 设置 el-scrollbar 自动滚动 */
const scrollRef = ref<any>(null)
let timer: any = null
const SCROLL_SPEED = 2 // 每次滚动的像素数,可以根据需要调整
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)
}
}
onMounted(() => {
startScroll()
})
onUnmounted(() => {
stopScroll()
})
</script>
<style scoped lang="scss">
.content {
position: absolute;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
display: flex;
flex-direction: column;
height: 400px; /* 容器高度必须设置,或者直接设置 scroll-container 的高度 */
border: 1px solid lightblue;
padding: 15px 20px;
.scroll-container {
width: 100%;
height: auto; /* 你可以根据需要调整高度 */
padding-right: 15px; /* 防止滚动条遮盖内容 */
}
:deep(.el-scrollbar__thumb) { // 修改滚动条的颜色
background: linear-gradient(180deg, #CBF2FA 0%, #30DCFF 100%);
}
.warn-item {
display: flex;
align-items: center;
border-bottom: 1px solid lightskyblue;
padding: 10px 0;
img {
width: 80px;
height: 100px;
object-fit: cover;
}
.info {
display: flex;
align-items: center;
justify-content: space-between;
height: 100px;
margin-left: 20px;
font-family: Alibaba PuHuiTi;
font-size: 20px;
font-weight: bolder;
color: #B4ABAB;
line-height: 25px;
letter-spacing: 0.05em;
font-feature-settings: "kern" on;
}
}
.warn-item:last-child {
border-bottom: none;
}
}
</style>
三、参考文章
在vue3 中,使用element-plus中的el-scrollbar,让内容元素自动滚动_element plus + ts 自动滚动-CSDN博客