smooth scroll to top

前端 未结 12 1225
眼角桃花
眼角桃花 2020-12-07 22:58

I\'ve bean searching for this for a few hours now and I have no solution. I want a smooth scroll to the top of the page. I already have smooth scrolling to separate anchors

12条回答
  •  忘掉有多难
    2020-12-07 23:28

    Here is my proposal implemented with ES6

    const scrollToTop = () => {
      const c = document.documentElement.scrollTop || document.body.scrollTop;
      if (c > 0) {
        window.requestAnimationFrame(scrollToTop);
        window.scrollTo(0, c - c / 8);
      }
    };
    scrollToTop();
    

    Tip: for slower motion of the scrolling, increase the hardcoded number 8. The bigger the number - the smoother/slower the scrolling.

提交回复
热议问题