为什么 smooth scroll 在 Vue 里有时候不生效?

闲人星宇 阅读 4

我在 Vue 项目里用 scrollIntoView({ behavior: 'smooth' }) 实现平滑滚动,但有时候完全没效果,直接跳转。试过加 CSS 的 scroll-behavior: smooth 也没用,是不是和 Vue 的响应式更新有冲突?

这是我的代码:

<template>
  <div id="container" style="height: 200px; overflow-y: auto;">
    <div v-for="i in 20" :key="i" :id="'item-' + i">Item {{ i }}</div>
  </div>
  <button @click="scrollToItem(15)">Scroll to 15</button>
</template>

<script>
export default {
  methods: {
    scrollToItem(index) {
      document.getElementById(item-${index})?.scrollIntoView({ behavior: 'smooth' });
    }
  }
}
</script>
我来解答 赞 1 收藏
二维码
手机扫码查看
暂无解答

暂无解答