滾動到頂部主要實現方式三種
1.<a href="#"></a>或者<a href="#top"></a>或者<a href="javascript:scrollTo(0,0)"></a>
2. window.scrollTo(0, 0);
3.document.body.scrollIntoView()
使用上面的方法是直接到頂部的,有的時候可能需要平滑些。
1.requestAnimationFrame
const scrollToTop = () => {
const c = document.documentElement.scrollTop || document.body.scrollTop;
if (c > 0) {
window.requestAnimationFrame(scrollToTop);
window.scrollTo(0, c - c / 8);
}
};
這個能平滑回到頂部,可以改變8的值
2.css
html {
scroll-behavior: smooth;
}
通過css實現,兼容性可能不太好。
3.scrollTo傳入對象
window.scrollTo({
left: 0,
top: 0,
behavior: 'smooth'
})
scrollTo可以傳入一個對象,left對應x,top對應y,behavior滾動行為,有的瀏覽器有問題。
我試了下a標簽也可以這么寫
<a href="javascript:
window.scrollTo({
left: 0,
top: 0,
behavior: 'smooth'
})
"></a>