0

我正在尝试用 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 Script 中慢慢向下滚动相同数量的像素

感谢您的任何想法。

4

1 回答 1

1
// 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)
    }
  })
}
于 2020-03-02T11:53:44.983 回答