Home > Net >  How to scroll div by a specific pixel in vue?
How to scroll div by a specific pixel in vue?

Time:12-30

I am trying to scroll up a div 10px by following method in Vue2 app:

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

However, instead of scroll to top 10px, it scrolls to the top. How can I scroll to a specific height.

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

CodePudding user response:

Good apprch will be, to scroll to the current scrollHeight of the reference element after updating the list.

Demo

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

CodePudding user response:

It did exactly what you asked it to do. It scrolled 10px from top.. That is how the calculation is done, from top. You may want to try..

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

/*
I don't know about Vue, but just try the method
*/
  • Related