【问题标题】:How to scroll div by a specific pixel in vue?如何在vue中按特定像素滚动div?
【发布时间】:2023-04-08 00:55:01
【问题描述】:

我正在尝试通过 Vue2 应用程序中的以下方法将 div 向上滚动 10px:

this.$refs.hello.scrollTo({ top: 10, left: 0, behavior: "smooth"});

但是,它不是滚动到顶部 10 像素,而是滚动到顶部。如何滚动到特定高度。

codesandbox 示例:https://codesandbox.io/s/youthful-blackwell-wl5x6?file=/src/components/HelloWorld.vue:531-630

【问题讨论】:

  • 它会滚动顶部 10px,这就是您编写的代码。你想要当前值 + 10... element.scrollTop 会给你当前的最高位置,在你的代码中添加 10
  • 你能检查答案abd关闭这个帖子吗?

标签: javascript vue.js vuejs2


【解决方案1】:

好方法是,在更新列表后滚动到引用元素的当前scrollHeight

演示

new Vue({
  el: '#app',
  name: "HelloWorld",
  props: {
    msg: String,
  },
  data() {
    return {
      list: [],
    };
  },
  mounted() {
    let i = 0;
    for (i = 0; i < 19; i++) {
      this.list.push(i);
    }
  },
  methods: {
    addItem() {
      this.list.push(0);
      setTimeout(() => {
        const targetTop = this.$refs.hello.scrollHeight;
        this.$refs.hello.scrollTo({
          top: targetTop,
          left: 0,
          behavior: "smooth",
        });
      })
    },
  }
})
.hello {
  overflow-y: auto;
  height: 200px;
  border: 1px solid black;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/vue/2.1.4/vue.js"></script>
<div id="app">
  <div class="hello" ref="hello">
    <h1>{{ msg }}</h1>
    <div v-for="item in list" :key="item">
      <div style="margin-bottom: 20px">{{ item }}</div>
    </div>
    <button @click="addItem">add</button>
  </div>
</div>

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-08-10
    • 2022-10-07
    • 2017-08-13
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-01-08
    相关资源
    最近更新 更多