單擊反應組件中的錨鏈接時,是否可以僅使用 CSS 進行平滑滾動?
...
render(
<a href="#smooth-link">Link To There</a>
....
<div id="smooth-link">
....
</div>
)
uj5u.com熱心網友回復:
有這個:
/**
* Smooth scrolling inside an element
*/
#my-element {
scroll-behavior: smooth;
}
/**
* Smooth scrolling on the whole document
*/
html {
scroll-behavior: smooth;
}
來源
但我覺得 JS 做得更好:
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
anchor.addEventListener('click', function (e) {
e.preventDefault();
document.querySelector(this.getAttribute('href')).scrollIntoView({
behavior: 'smooth'
});
});
});
所以你可以試一試:docs
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/460218.html
標籤:javascript css 反应 下一个.js
下一篇:掛載的生命周期鉤子中的異步等待
