如何使用 window.scrollTo()获得平滑的效果

我可以滚动到200px 使用以下

btn.addEventListener("click", function(){
window.scrollTo(0,200);
})

但我想要一个光滑的滚动效果。我该怎么做呢?

196920 次浏览

2018 Update

Now you can use just window.scrollTo({ top: 0, behavior: 'smooth' }) to get the page scrolled with a smooth effect.

const btn = document.getElementById('elem');


btn.addEventListener('click', () => window.scrollTo({
top: 400,
behavior: 'smooth',
}));
#x {
height: 1000px;
background: lightblue;
}
<div id='x'>
<button id='elem'>Click to scroll</button>
</div>

Older solutions

You can do something like this:

var btn = document.getElementById('x');


btn.addEventListener("click", function() {
var i = 10;
var int = setInterval(function() {
window.scrollTo(0, i);
i += 10;
if (i >= 200) clearInterval(int);
}, 20);
})
body {
background: #3a2613;
height: 600px;
}
<button id='x'>click</button>

ES6 recursive approach:

const btn = document.getElementById('elem');


const smoothScroll = (h) => {
let i = h || 0;
if (i < 200) {
setTimeout(() => {
window.scrollTo(0, i);
smoothScroll(i + 10);
}, 10);
}
}


btn.addEventListener('click', () => smoothScroll());
body {
background: #9a6432;
height: 600px;
}
<button id='elem'>click</button>

$('html, body').animate({scrollTop:1200},'50');

You can do this!