如果您想了解更全面的平滑滚动方法列表,请查看我的答案这里。
为了在精确的时间内滚动到特定的位置,可以使用
window.requestAnimationFrame
,每次计算适当的当前位置。如果不支持
requestAnimationFrame
,可以使用
setTimeout
以类似的效果进行操作。要滚动到页面顶部,请使用以下函数,并将位置设置为
0
。
function scrollToSmoothly(pos, time) {
var currentPos = window.pageYOffset;
var start = null;
if(time == null) time = 500;
pos = +pos, time = +time;
window.requestAnimationFrame(function step(currentTime) {
start = !start ? currentTime : start;
var progress = currentTime - start;
if (currentPos < pos) {
window.scrollTo(0, ((pos - currentPos) * progress / time) + currentPos);
} else {
window.scrollTo(0, currentPos - ((currentPos - pos) * progress / time));
}
if (progress < time) {
window.requestAnimationFrame(step);
} else {
window.scrollTo(0, pos);
}
});
}
function scrollToSmoothly(pos, time) {
var currentPos = window.pageYOffset;
var start = null;
if(time == null) time = 500;
pos = +pos, time = +time;
window.requestAnimationFrame(function step(currentTime) {
start = !start ? currentTime : start;
var progress = currentTime - start;
if (currentPos < pos) {
window.scrollTo(0, ((pos - currentPos) * progress / time) + currentPos);
} else {
window.scrollTo(0, currentPos - ((currentPos - pos) * progress / time));
}
if (progress < time) {
window.requestAnimationFrame(step);
} else {
window.scrollTo(0, pos);
}
});
}
window.scrollTo(0, 2000);
document.querySelector('button').addEventListener('click', function(e){
scrollToSmoothly(0, 700);
});
<button style="margin: 2000px 0;">Smooth scroll to top</button>
SmoothScroll.js库也可以使用,它处理更复杂的情况,例如平滑地垂直和水平滚动,在其他容器元素内滚动,不同的缓动行为,相对于当前位置滚动等等。
smoothScroll({yPos: 'start', duration: 700});
smoothScroll({yPos: 0, duration: 700});
window.scrollTo(0, 2000);
document.querySelector('button').addEventListener('click', function(e){
smoothScroll({yPos: 'start', duration: 700});
});
<script src="https://cdn.jsdelivr.net/gh/LieutenantPeacock/SmoothScroll@1.2.0/src/smoothscroll.min.js" integrity="sha384-UdJHYJK9eDBy7vML0TvJGlCpvrJhCuOPGTc7tHbA+jHEgCgjWpPbmMvmd/2bzdXU" crossorigin="anonymous"></script>
<button style="margin: 2000px 0;">Smooth scroll to top</button>
另外,您可以将选项对象传递给 window.scroll
,并将行为设置为平滑滚动到特定的 x 和 y 位置,或者使用 window.scrollBy
从当前位置滚动一定量:
window.scroll({
top: 2500,
left: 0,
behavior: 'smooth'
});
window.scrollBy({
top: 100,
left: 0,
behavior: 'smooth'
});
window.scrollTo(0, 2000);
document.querySelector('button').addEventListener('click', function(e){
window.scroll({top: 0, left: 0, behavior: 'smooth'});
});
<button style="margin: 2000px 0;">Smooth scroll to top</button>
现代浏览器支持
scroll-behavior
CSS属性, 可以用于使文档中的滚动平滑(无需使用JavaScript)。
window.scrollTo(0, 2000);
document.querySelector('button').addEventListener('click', function(e){
window.scrollTo(0, 0);
});
html, body {
scroll-behavior: smooth;
}
<button style="margin: 2000px 0;">Scroll to top (JavaScript)</button>
<a href="#">Link to smoothly scroll to top of page (no JavaScript)</a>