【VUE】实现自动滚动

一、场景

当内容超出元素固定高度时可以进行自动滚动。

二、实现

首先,给需要自动滚动的元素设定统一的name,方便后续滚动方法获取元素的信息,我这里举例统一用scrollBox:

<el-card class="text" name="scrollBox">
  文本内容
</el-card>

其次,给需要自动滚动的元素设置样式,要满足高度固定,超出高度时出现滚动栏:

height: 600px;
overflow: auto;

最后,就是自动滚动方法:
scrollHeight为元素展开的全部高度,scrollTop为滚动滑块所在的位置高度,clientHeight为滚动滑块的高度。

    updateScrollTop() {
      const scrollList = document.getElementsByName('scrollBox')
      for (let i = 0; i < scrollList.length; i++) {
        const x = scrollList[i]
        this.scrollThen(x).then()
      }
    },
    async scrollThen(x) {
      do {
        await new Promise(resolve => {
          setTimeout(() => {
            resolve()
          }, 100)
        })
        if (parseFloat(x.clientHeight / x.scrollHeight) < 0.8) {
          if (x.scrollHeight - x.scrollTop === x.clientHeight) {
            x.scrollTop = 0
          } else {
            x.scrollTop++
          }
        }
      } while (true)
    }

然后在页面初始化时,调用滚动方法即可:

  mounted() {
    this.updateScrollTop()
  }

猜你喜欢

转载自blog.csdn.net/qq_45050480/article/details/128441087
今日推荐