[英]Smooth scrolling when clicking an anchor link on react/next.js
單擊反應組件中的錨鏈接時,是否可以僅使用 CSS 進行平滑滾動?
...
render(
<a href="#smooth-link">Link To There</a>
....
<div id="smooth-link">
....
</div>
)
有這個:
/**
* 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
使用npm i react-scroll
package
您必須在<Link>
標記內的錨標記上添加點擊偵聽器:
<Link href="#about">
<a className="nav-item" onClick={scrollHandle} id="about-">About Us</a>
</Link>
滾動處理程序:-
const scrollHandle = (e) => {
e.preventDefault();
let id = e.target.id;
let position = document.getElementById(id.slice(0, id.length - 1)); //removing extra last - (dash)
window.location.href = "#" + id.slice(0, id.length - 1); // changing the url
position && position.scrollIntoView({ behavior: "smooth", block: "start" }) //scrolling the page
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.