方案一 :

基于js实现平滑滚动的效果

    // 实现滚动条平滑滚动的方法
    scrollToCmtList() {
      // 1.1 返回文档在垂直方向已滚动的像素值
      const now = window.scrollY
      // 1.2 目标位置(文章信息区域的高度)
      let dist = document.querySelector('.article-container').offsetHeight
      // 1.3 可滚动高度 = 整个文档的高度 - 浏览器窗口的视口(viewport)高度
      const avalibleHeight =
        document.documentElement.scrollHeight - window.innerHeight

      // 2.1 如果【目标高度】 大于 【可滚动的高度】
      if (dist > avalibleHeight) {
        // 2.2 就把目标高度,设置为可滚动的高度
        dist = avalibleHeight
      }

      // 3. 动态计算出步长值
      const step = (dist - now) / 10

      setTimeout(() => {
        // 4.2 如果当前的滚动的距离不大于 1px,则直接滚动到目标位置,并退出递归
        if (Math.abs(step) <= 1) {
          return window.scrollTo(0, dist)
        }
        // 4.1 每隔 10ms 执行一次滚动,并递归地进行下一次的滚动
        window.scrollTo(0, now + step)
        this.scrollToCmtList()
      }, 10)
    }

方案二 :

基于 popmotion 这个第三方包,可以轻松实现平滑滚动的效果

1. 运行如下的命令,安装 popmotion 这个依赖包:

npm install popmotion@9.3.5 -S

2. 在需要用到的组件中,从 popmotion 中按需导入 animate 函数:

// 从 popmotion 中按需导入 animate 动画函数
import { animate } from 'popmotion'

3. 在需要用到的组件中,为组件绑定点击事件处理函数:

<van-icon name="comment-o" size="20" @click="scrollToCmtList" />

4. 在组件的 methods 节点下声明 scrollToCmtList 方法:

// 滚动到评论的列表区域
scrollToCmtList() {
  // 1. 当前滚动条的位置
  const now = window.scrollY
  // 2. 目标位置(文章信息区域的高度)
  const dist = document.querySelector('.article-container').offsetHeight

  // 3. 实现滚动动画
  animate({
    from: now, // 当前的位置
    to: dist,  // 目标位置
    onUpdate: latest => window.scrollTo(0, latest)
  })
}

Popmotion的参考文档:

 Popmotion —— 流动你的页面 - 知乎

Popmotion: The animator's JavaScript toolbox

Popmotion —— 流动你的页面 - 知乎开始 | popmotion 中文文档

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐