关于为滚动条加上过渡效果

由于scrollTop是js属性设置,所以css的属性基本无法为滚动条设置过渡效果,但是有一个css属性可以完成一点效果。

scroll-behavior: smooth; 当增加这一css的后,会发现效果变得生硬,完全用不了啊!

网络上通常的解决方法是写一个滚动函数:

scrolling (el, duration, targetOffsetTop) {
      // 获取当前滚动位置
      let currentScrollTop = el.scrollTop;
      // 计算滚动距离
      let distance = targetOffsetTop - currentScrollTop;
      // 计算每一帧滚动的距离和时间间隔
      let scrollStep = Math.PI / (duration / 15);
      let cosParameter = (targetOffsetTop - currentScrollTop) / 2;

      let scrollCount = 0;
      let scrollMargin;

      // 定义滚动动画函数
      function smoothScroll() {
        // 设置下一帧滚动位置
        let targetScrollTop = currentScrollTop + cosParameter - cosParameter * Math.cos(scrollCount * scrollStep);
        el.scrollTop = targetScrollTop;

        // 更新滚动计数器和滚动边距
        scrollCount++;
        scrollMargin = distance - cosParameter + cosParameter * Math.cos(scrollCount * scrollStep);
        // 判断是否继续滚动
        if (Math.abs(scrollMargin) > 0.2) {
          requestAnimationFrame(smoothScroll);
        }
      }
      // 调用滚动动画函数
      smoothScroll();
    }

当然肯定有更好的办法,如果你不考虑怎么去过渡:

el.scrollTo({top: 0, behavior: 'smooth'})

其中, top指定距离顶部的位置是多少,behavior是滚动方式,这样写完发现效果实现了!

补丁

最近遇到了横向滚动,点击菜单会添加这一项的标签,一直在通过各种距离想让滚动条滚动到对应的标签附近,结果很失败,查了一些方法,发现是我无知了

 this.$refs.activeItem[0].scrollIntoView({ behavior: "smooth", inline: "center" });

ok 只需要一个scrollIntoView方法,只需要找到激活的标签,然后调用方法,看来得恶补下基础知识了。

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值