簡體   English   中英

單擊 react/next.js 上的錨鏈接時平滑滾動

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM