<script setup>
const containerRef = ref(null) // 用于存储滚动容器的引用
const entryRefs = ref([]) // 用于存储每个条目的引用
// 设置条目引用的函数
const setEntryRef = (el, index) => {
if (el) {
entryRefs.value[index] = el // 使用 index 确保正确存储每个条目的引用
}
}
// 自定义的平滑滚动函数
function smoothScroll(target, duration) {
const container = containerRef.value
const targetPosition = target.offsetTop - container.offsetTop
const startPosition = container.scrollTop
const distance = targetPosition - startPosition
let startTime = null
function animation(currentTime) {
if (startTime === null) startTime = currentTime
const timeElapsed = currentTime - startTime
const run = ease(timeElapsed, startPosition, distance, duration)
container.scrollTop = run
if (timeElapsed < duration) requestAnimationFrame(animation)
}
function ease(t, b, c, d) {
t /= d / 2
if (t < 1) return (c / 2) * t * t + b
t--
return (-c / 2) * (t * (t - 2) - 1) + b
}
requestAnimationFrame(animation)
}
// 使用
// entryRefs.value[currentIndex] 根据自身需求获取到相应的元素
smoothScroll(entryRefs.value[currentIndex], 300) // 自定义滚动时长为300毫秒
</script>
div ref="containerRef" class="container">
<div
:ref="(el) => setEntryRef(el, index)"
class="item"
>
滚动的元素
</div>
</div>