javascript - 如何获得 Chrome 的精确平滑滚动功能?

标签 javascript css scroll smooth-scrolling

当用户单击我页面上的按钮时,它会在其下方创建一个新元素,然后向下滚动。我希望这可以顺利完成,并且可以像这样完成:window.scroll({ top: document.body.scrollHeight, behavior: "smooth" });但是,这在 Safari 上不起作用,因此看来我需要使用自定义函数来获得此功能。
我四处搜寻,发现了这个(当前答案,但不是最理想的):

doScrolling = (elementY, duration) => { 
  let startingY = window.pageYOffset;
  let diff = elementY - startingY;
  var start;

  // Bootstrap our animation - it will get called right before next frame shall be rendered.
  window.requestAnimationFrame(function step(timestamp) {
    if (!start) { start = timestamp; }
    // Elapsed milliseconds since start of scrolling.
    let time = timestamp - start;
    // Get percent of completion in range [0, 1].
    let percent = Math.min(time / duration, 1);

    window.scrollTo(0, startingY + diff * percent);

    let isScrollAtBottom = (window.innerHeight + window.pageYOffset) >= document.body.scrollHeight - 3;

    if (isScrollAtBottom) { return; }

    // Proceed with animation as long as we wanted it to.
    if (time < duration) {
      window.requestAnimationFrame(step);
    }
  })
}
像这样调用:this.doScrolling(document.body.scrollHeight, 750);这似乎可行,但它似乎与 window.scroll 的语义不同.
一方面,您需要指定持续时间,而使用 window.scroll这是暗示的。
其次,好像window.scroll使用不同的过渡类型?很难说,但感觉更像 ease而不是 linear过渡,开始缓慢,然后快速,然后减速停止。
是否可以修改上述函数以模仿 window.scroll 的确切语义?这样您就无法分辨调用两者之间的区别?
澄清一下,我不需要克隆 window.scroll 的所有功能。 .我唯一需要的是能够以流畅的方式滚动到给定位置(在我的情况下它始终是页面的末尾)。我在上面的问题中提供的功能几乎是完美的,只是它有点笨拙并且感觉不像 window.scroll 那样流畅.我想可能是动画风格?很难说为什么它看起来“更糟”,因为它是如此之快。

最佳答案

您可以尝试使用 AnimeJS
添加<script src="path/to/anime.min.js"></script>到您的 HTML 页面
或通过 CDN 访问 https://cdnjs.cloudflare.com/ajax/libs/animejs/3.2.0/anime.min.js接着

doScrolling = (elementY) => {
  const startingY = window.pageYOffset
  const diff = elementY - startingY

  const obj = {
    pos: startingY
  }

  const anime({
    targets: obj,
    pos: startingY + diff,
    round: 1,
    easing: 'easeInOutQuad',
    update: function() {
      window.scrollTo(0, obj.pos)
    }
  }).play()
}

关于javascript - 如何获得 Chrome 的精确平滑滚动功能?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64054992/

相关文章:

android - Firefox for Android 拒绝显示列表项,这是一个普通的 HTML 页面。为什么?

android - 褪色边缘仅在顶部和左侧起作用

javascript - 如何检测输入 jQuery 的值变化?

html - 垂直 DIV 液体布局问题

javascript - 是什么导致未捕获的类型错误 : number is not a function?

jquery-visible - 可见的整个元素

javascript - react : Parent component refs not accessible to newly mounted child component?

html - 在除 Firefox 之外的所有浏览器中都出现跳动滚动

javascript - 根据json数据属性动态生成多个div

javascript - 如何在 JavaScript 中将选项附加到 optgroup?