简体   繁体   English

单击 react/next.js 上的锚链接时平滑滚动

[英]Smooth scrolling when clicking an anchor link on react/next.js

Is it possible using only CSS to make smooth scrolling when clicking an anchor link in react component?单击反应组件中的锚链接时,是否可以仅使用 CSS 进行平滑滚动?

...
render(
    <a href="#smooth-link">Link To There</a>
    ....
    <div id="smooth-link">
        ....
    </div>
)

There's this:有这个:

/**
 * Smooth scrolling inside an element
 */
#my-element {
    scroll-behavior: smooth;
}

/**
 * Smooth scrolling on the whole document
 */
html {
    scroll-behavior: smooth;
}

Source 资源

But I feel like JS does a better job:但我觉得 JS 做得更好:

document.querySelectorAll('a[href^="#"]').forEach(anchor => {
    anchor.addEventListener('click', function (e) {
        e.preventDefault();

        document.querySelector(this.getAttribute('href')).scrollIntoView({
            behavior: 'smooth'
        });
    });
});

So you could give that a try: docs所以你可以试一试: docs

use npm i react-scroll package使用npm i react-scroll package

You have to add click listener on anchor tag inside of <Link> tag:您必须在<Link>标记内的锚标记上添加点击侦听器:

 <Link href="#about">
     <a className="nav-item" onClick={scrollHandle} id="about-">About Us</a>
 </Link>

scrollHandler:-滚动处理程序:-

 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