1.window.scrollTo()
// left 是文檔中的橫軸坐標(biāo)。
// top 是文檔中的縱軸坐標(biāo)。
window.scrollTo({
top: 1000,
left: 0,
behavior: "smooth"
})
or
// window.scrollTo(x, y);
// x 是文檔中的橫軸坐標(biāo)。
// y 是文檔中的縱軸坐標(biāo)。
window.scrollTo(0, 1000);
html {
scroll-behavior: smooth;
}
2.scrollIntoView
document.getElementById(id).scrollIntoView({ behavior: 'smooth' })
or
document.getElementById(id).scrollIntoView();
html {
scroll-behavior: smooth;
}
以上代碼IE、Edge 支持不是很好,下面兼容寫法
3. smoothscroll
npm install smoothscroll-polyfill --save
import smoothscroll from 'smoothscroll-polyfill';
// kick off the polyfill!
smoothscroll.polyfill();
window.scroll({ top: 2500, left: 0, behavior: 'smooth' });
element.scroll({ top: 0, left: 0, behavior: 'smooth' });
document.querySelector('.hello').scrollIntoView({ behavior: 'smooth' });
document.querySelector('header').scrollIntoView({ behavior: 'smooth' });
element.scrollBy({ top: 100, left: 0, behavior: 'smooth' });
更多去官網(wǎng)看:http://iamdustan.com/smoothscroll/
其他實(shí)現(xiàn):jump.js