记录用vue3实现了一个自动滚动的内容区域,先上图图
1.用处:
用于实现任意内容的自动滚动,鼠标进入可停止滚动
2.实现原理:
创建一个dom为ul,赋值为当前内容,然后拷贝这个dom赋值给第二个ul,然后判断屏幕高度跟滚动高度对比,利用requestAnimationFrame动画实现滚动
3.注意事项:
利用插槽,可放置任意滚动内容
组件:
<template>
<div
class="scrollContainer"
:key="currentTime"
:style="{ height: `${height}px` }"
>
<ul class="scrollBody" ref="wrapperDom" :style="{ height: `${height}px` }">
<ul ref="childDom1" @mouseenter="handleEnter" @mouseleave="handleLeave">
<slot name="scroll-content"></slot>
</ul>
<ul ref="childDom2"></ul>
</ul>
</div>
</template>
<script setup lang="ts">
import { onMounted, watch, ref, onBeforeUnmount, computed, nextTick } from 'vue'
interface ViewProps {
height: number
speed?: number
}
export interface TableColumn {
key: string
title: string
width: number
render?: (index: number, data: Record<string, any>, text: any) => any
onClick?: (data: Record<string, any>) => void
}
const props = defineProps<ViewProps>()
const { height, speed = 0.4 } = props
const wrapperDom = ref<any>()
const childDom1 = ref<any>()
const childDom2 = ref<any>()
const currentTime = ref(new Date().getTime())
let count = 0
let reqAnimation: number
onMounted(() => {
nextTick(() => {
reqAnimation = window.requestAnimationFrame(taskStart)
})
})
onBeforeUnmount(() => {
handleEnter()
})
// 开启滚动,当判断当前盒子滚动条所在高度大于dom1的高度后,将滚动条高度设置为0
const taskStart = () => {
if (
childDom1.value?.clientHeight > wrapperDom.value?.clientHeight &&
!childDom2.value.height
) {
childDom2.value.innerHTML = childDom1.value.innerHTML
}
// 设置滚动速度
if (wrapperDom.value.scrollTop >= childDom1.value.scrollHeight) {
wrapperDom.value.scrollTop = 0
count = 0
} else {
count += speed
wrapperDom.value.scrollTop = count
}
reqAnimation = window.requestAnimationFrame(taskStart)
}
const handleEnter = () => {
window.cancelAnimationFrame(reqAnimation)
}
const handleLeave = () => {
reqAnimation = window.requestAnimationFrame(taskStart)
}
</script>
<style lang="scss" scoped>
.scrollContainer {
width: 100%;
div {
text-align: center;
display: inline-block;
margin: 0;
font-size: 14px;
font-weight: normal;
font-stretch: normal;
letter-spacing: 0;
opacity: 0.9;
}
.scrollHead {
display: flex;
align-items: center;
background-color: rgba(33, 60, 93, 0.55);
div {
font-size: 14px;
font-stretch: normal;
letter-spacing: 0;
font-family: MicrosoftYaHei, sans-serif;
font-weight: bold;
color: #ffffff;
opacity: 0.47;
}
}
.scrollBody {
overflow-y: scroll;
width: 100%;
scrollbar-width: none;
-ms-overflow-style: none;
ul {
height: auto;
padding: 0;
margin: 0;
}
}
}
</style>
父组件使用:
<ScrollContainer :height="200">
<template v-slot:scroll-content>
<div class="content">
</div>
</template>
</ScrollContainer>