在Java Script中缓慢向下滚动X个像素



我正在尝试用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)
}
})
}

最新更新