在 Java 脚本中缓慢向下滚动 X 像素

Scroll down X pixels slowly in Java Script

我正在尝试在 HTML 中为学校制作一些东西,当按下向下箭头时,它会向下滚动到下一部分。

当前,站点向下滚动 ((window.innerHeight+(window.innerHeight*0.1))+1) 输出的像素数。

这是我的 Java 脚本代码:

document.onkeydown = checkKey;
function checkKey(e) {
  e = e || window.event;
  if (e.keyCode == '40') {
    document.getElementById("mainbody").scrollBy({
      top: ((window.innerHeight+(window.innerHeight*0.1))+1),
      behavior: 'smooth'
    });
  }
}

代码使向下滚动的速度太快了。有什么方法可以在纯 Java 脚本中 缓慢地 向下滚动 相同数量的像素 吗?

感谢任何想法。

// elementY: is the vertical offset of the whole page
// duration: how long do you want the scroll last
// for example: doScrolling(0, 300) will scroll to the very beginning of page
// in 300ms
function doScrolling(elementY, duration) {
  const startingY = window.pageYOffset
  const diff = elementY - startingY
  let 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.
    const time = timestamp - start
    // Get percent of completion in range [0, 1].
    const percent = Math.min(time / duration, 1)

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

    // Proceed with animation as long as we wanted it to.
    if (time < duration) {
      window.requestAnimationFrame(step)
    }
  })
}