Dre*_*mhi 8 javascript css reactjs next.js
单击反应组件中的锚链接时,是否可以仅使用 CSS 来实现平滑滚动?
...
render(
<a href="#smooth-link">Link To There</a>
....
<div id="smooth-link">
....
</div>
)
Run Code Online (Sandbox Code Playgroud)
小智 9
有这个:
/**
* Smooth scrolling inside an element
*/
#my-element {
scroll-behavior: smooth;
}
/**
* Smooth scrolling on the whole document
*/
html {
scroll-behavior: smooth;
}
Run Code Online (Sandbox Code Playgroud)
但我觉得 JS 做得更好:
document.querySelectorAll('a[href^="#"]').forEach(anchor => {
anchor.addEventListener('click', function (e) {
e.preventDefault();
document.querySelector(this.getAttribute('href')).scrollIntoView({
behavior: 'smooth'
});
});
});
Run Code Online (Sandbox Code Playgroud)
所以你可以尝试一下:文档
我正在使用tailwindcss
,但它也可以在没有 tailwindcss 的情况下工作。您只需要添加scroll-behavior:smooth
forhtml
标签即可。转到.css
项目中的全局文件。在顶部添加这一行。
html {
scroll-behavior: smooth;
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
17303 次 |
最近记录: |