Vue 点击按钮滑动到指定位置

471 阅读1分钟

方法1:

<div class="box">
    <div @click="toscroll"></div>
    ....
    ....
    ....
    <div ref="scrollbox"></div>
</div>
     methods: {
        toScroll() {
          const scrollbox = this.$refs.scrollbox;
          if (scrollbox) {
            setTimeout(() => {
              scrollbox.scrollIntoView(true);
            }, 500);
          }
       }
      }

方法2: 要求平滑的滑动到指定的位置

<div class="box">
    <div @click="toscroll"></div>
    ....
    ....
    ....
    <div ref="scrollbox"></div>
</div>
     methods: {
         toScroll() {
          const CH = document.documentElement.clientHeight || document.body.clientHeight; //一屏
          const H = this.$refs.scrollbox.clientHeight;
          const T = this.$refs.scrollbox.offsetTop;
          this.startMove(T - CH + H); //调用methods中的另外一个方法
        },
        startMove(top) {
          let timer = "";
          let speed = 5;
          timer = setInterval(function () {
            let t = document.documentElement.scrollTop || document.body.scrollTop; //获取滚动条位置
            if (t < top) {
              if (document.documentElement.scrollTop >= 0) {
                document.documentElement.scrollTop += speed; //获取当前滚动条位置增加speed变量高度
              } else {
                document.body.scrollTop += speed;
              }
              speed += 5;
            } else {
              clearInterval(timer); //清除定时器
            }
          }, 50);
        },
     } 

最外层div不可设置高度

.box {
 width: 100%;
 overflow: scroll;
 scroll-behavior: smooth; //平滑
}