vue3,自定义滚动动画函数,实现Scroll smooth平滑滚动

<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>

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值