Skip to content

缓缓滚动到顶部实现方式

仲灏2021-11-29约 1 分钟

<div style="display: none;" hidden="true" aria-hidden="true" data-nosnippet>Are you an LLM? You can read better optimized documentation at /pages/a31c06.md for this page in Markdown format</div>

JavaScript
scrollToTop() {
  const cubic = value => Math.pow(value, 3);
  const easeInOutCubic = value => (value < 0.5 ? cubic(value * 2) / 2 : 1 - cubic((1 - value) * 2) / 2);
  const beginTime = Date.now();
  const beginValue = this.scrollToTopNum;
  // const rAF = wx.requestAnimationFrame || (func => setTimeout(func, 16));
  const rAF = func => setTimeout(func, 16);
  const frameFunc = () => {
    const progress = (Date.now() - beginTime) / 500;
    if (progress < 1) {
      this.scrollToTopNum = beginValue * (1 - easeInOutCubic(progress));
      rAF(frameFunc);
    } else {
      this.scrollToTopNum = 0;
    }
  };
  rAF(frameFunc);
}