在下一个js中平滑滚动

问题描述 投票:0回答:11

如何在 Next.js 中将滚动效果设置为平滑(全局)? 我尝试在全局 css 上执行此操作,但它停用了 Next js 已有的滚动到顶部功能。

我也尝试了在互联网上找到的这个解决方案,但它也不起作用。

 componentDidMount() {
 Router.events.on('routeChangeComplete', () => {
    window.scroll({
       top: 0,
       left: 0,
       behavior: 'smooth'
    });
 });

}

reactjs next.js smooth-scrolling
11个回答
38
投票

在 html 或 body 中添加滚动行为:平滑。 然后添加进去

<Link href="#someid" scroll={false}>

有效


12
投票

只需将

style={{scrollBehavior:'smooth'}
放入“_document.tsx”文件中的标签 Html 中即可。

喜欢:

class MyDocument extends Document {
  static async getInitialProps(ctx: DocumentContext) {
    const initialProps = await Document.getInitialProps(ctx);
    return { ...initialProps };
  }

  render() {
    return (
      <Html className='scroll-smooth' style={{scrollBehavior:'smooth'}}>
        <Head>
          <link rel='icon' href='/favicon.ico' />
          <meta
            name='description'
            content='A place to find a great film to watch'
          />
        </Head>
        <body className='bg-gray-50 screen'>
          <Main />
          <NextScript />
        </body>
      </Html>
    );
  }
}

2
投票

如果您使用类组件,您可以复制并粘贴以下代码:

import React, { Component } from 'react';

export default class ScrollToTopButton extends Component {
  // this is function that will scroll to the top of the page when the button is clicked
  scrollToTop = () => {
    window.scrollTo({
      top: 0,
      behavior: 'smooth',
    });
  };

  render() {
    return (
      <>
        <div> textInComponent </div>
        <div> textInComponent </div>
        <div> textInComponent </div>
        <div> textInComponent </div>
        <div> textInComponent </div>
        <div> textInComponent </div>
        <div> textInComponent </div>
        <div> textInComponent </div>
        <div> textInComponent </div>
        <div> textInComponent </div>
        <div> textInComponent </div>
        <div> textInComponent </div>
        <div> textInComponent </div>
        <div> textInComponent </div>
        <div> textInComponent </div>
        <div> textInComponent </div>
        <div> textInComponent </div>
        <div> textInComponent </div>
        <div> textInComponent </div>
        <div> textInComponent </div>
        <div> textInComponent </div>
        <div> textInComponent </div>
        <div> textInComponent </div>
        <div> textInComponent </div>
        <div> textInComponent </div>
        <div> textInComponent </div>
        <div> textInComponent </div>
        <div> textInComponent </div>
        <div> textInComponent </div>
        <div> textInComponent </div>
        <div> textInComponent </div>
        <div> textInComponent </div>
        <div> textInComponent </div>
        <div> textInComponent </div>
        <div> textInComponent </div>
        <div> textInComponent </div>
        <div> textInComponent </div>
        <div> textInComponent </div>
        <div> textInComponent </div>
        <div> textInComponent </div>
        <div> textInComponent </div>
        <div> textInComponent </div>
        <div> textInComponent </div>
        {/* This is the button that will go up */}
        <button onClick={() => this.scrollToTop()}> textInComponent </button>
      </>
    );
  }
}

或者,如果您要实现函数组件

import React, { Component } from 'react';

function ScrollToTopButton() {
  // this is function that will scroll to the top of the page when the button is clicked
  const scrollToTop = () => {
    window.scrollTo({
      top: 0,
      behavior: 'smooth',
    });
  };

  return (
    <>
      <div> textInComponent </div>
      <div> textInComponent </div>
      <div> textInComponent </div>
      <div> textInComponent </div>
      <div> textInComponent </div>
      <div> textInComponent </div>
      <div> textInComponent </div>
      <div> textInComponent </div>
      <div> textInComponent </div>
      <div> textInComponent </div>
      <div> textInComponent </div>
      <div> textInComponent </div>
      <div> textInComponent </div>
      <div> textInComponent </div>
      <div> textInComponent </div>
      <div> textInComponent </div>
      <div> textInComponent </div>
      <div> textInComponent </div>
      <div> textInComponent </div>
      <div> textInComponent </div>
      <div> textInComponent </div>
      <div> textInComponent </div>
      <div> textInComponent </div>
      <div> textInComponent </div>
      <div> textInComponent </div>
      <div> textInComponent </div>
      <div> textInComponent </div>
      <div> textInComponent </div>
      <div> textInComponent </div>
      <div> textInComponent </div>
      <div> textInComponent </div>
      <div> textInComponent </div>
      <div> textInComponent </div>
      <div> textInComponent </div>
      <div> textInComponent </div>
      <div> textInComponent </div>
      <div> textInComponent </div>
      <div> textInComponent </div>
      <div> textInComponent </div>
      <div> textInComponent </div>
      <div> textInComponent </div>
      <div> textInComponent </div>
      <div> textInComponent </div>
      {/* This is the button that will go up */}
      <button onClick={() => scrollToTop()}> textInComponent </button>
    </>
  );
}

export default ScrollToTopButton;

我不知道如何描述这段代码,但它对我有效;我希望它有帮助!


1
投票

转到全局或主 css 文件夹并写入:

html{scroll-behavior: smooth;}

或者,如果您使用的是 Tailwind,请进入您的

_document.js
文件并应用以下内容:

import { Html, Head, Main, NextScript } from 'next/document'

export default function Document() {
  return (
    <Html lang="en" className='scroll-smooth'>
      <Head />
      <body>
        <Main />
        <NextScript />
      </body>
    </Html>
  )
}

如果您希望在同一页面上的链接之间平滑滚动,请在操作

scroll
组件上的
next/link
属性时执行类似的操作:

<Link href="/#skills" scroll={false}>
    <li className="ml-10 text-sm uppercase hover:border-b">Skills</li>
</Link>

也不要忘记在要导航到的 div 上设置

id='whatever'

希望这有帮助! :)


1
投票

以下代码对我来说效果很好。

<Link className="navlinks1 whitespace-nowrap" href="/#faqs" onClick={(e) => {
            e.preventDefault();
            document.getElementById("faqs").scrollIntoView({ behavior: "smooth" });
          }}>
            FAQs
          </Link>

0
投票

我解决了!你可以使用 npm 包来做到这一点(不是全局的,但它工作得很好)

react-scroll
这是链接:https://www.npmjs.com/package/react-scroll


0
投票

我们可以在

_document.tsx
中实现文档组件,而不是继承。创建功能组件对我有用。

_document.tsx

import { Html, Head, Main, NextScript } from "next/document";

export default function Document() {
  return (
    <Html className='scroll-smooth' >
      <Head/>
      <body>
        <Main />
        <NextScript />
      </body>
    </Html>
  );
}

https://nextjs.org/docs/advanced-features/custom-document


0
投票

这在 NextJS 中对我来说效果很好

在全局.css中

* {
    scroll-behavior: smooth;
}

我使用过以下 href 代码:

<a href="#features" className={`${styles.feature} pointer`}>Features</a>

0
投票

scroll={false}
添加到 Link 组件或仅使用 HTML 的锚标记 解决了这个问题。

<Link scroll={false} href='#idname'>
 link name
</Link>

<a href='#idname'>
 link name
</a>

0
投票

对于任何使用 Next 13(应用程序目录)及以上版本并希望能够滚动到当前页面上的特定部分或导航到另一个页面并自动滚动到特定部分的人,像我一样已经尝试了这里的所有内容,但没有成功工作然后查看这个答案。

首先创建一个接受 Id 字符串并将元素滚动到视图中的函数。

// Handles scrolling of Element to view
export function scrollElementToView(scrollToId: string) {
  const element = document.querySelector(`#${scrollToId}`) as HTMLElement;

  const elRect = element.getBoundingClientRect();

  const scrollDistance = elRect.top + window.scrollY;

  // Incase you want to offset the scroll To view Position.
  const offset = Number(element.getAttribute('data-scroll-to-view-offset')) || 0;

  window.scrollTo({
    top: scrollDistance + offset,
    behavior: 'smooth'
  })
}

然后创建一个文件名ScrollToLinkGlobalComponent并添加

'use client';
import React, { useEffect } from 'react';
import { useSearchParams } from 'next/navigation';
import { scrollElementToView } from //whereEver you keep the file



function ScrollToLinkGlobalComponent() {
  const searchParams = useSearchParams();

  useEffect(() => {
    // get element Id from searchParams
    const scrollToId = searchParams.get("scrollToId");

    if (!scrollToId) return; // return if there is none

    scrollElementToView(scrollToId);

  }, [searchParams])

  return null
}

export default ScrollToLinkGlobalComponent

现在将 ScrollToLinkGlobalComponent 添加到您的 RootLayout 中。它应该看起来像这样

*** Imports ***


export default function RootLayout({
  children,
}: {
  children: React.ReactNode
}) {
  return (
    <html lang="en" className={nunitoSansFont.className}>
      <body>
          {children}
          <ScrollToLinkGlobalComponent />
      </body>
    </html>
  )
}

然后创建一个 ScrollToLink 组件来扩展默认的 Next Link 组件。

'use client';
import Link from 'next/link';
import React, { ComponentPropsWithRef } from 'react';
import { useSearchParams } from 'next/navigation';
import { scrollElementToView } from //whereEver you keep the file


interface PropTypes extends ComponentPropsWithRef<typeof Link> {
    scrollToId: string
}



function ScrollToLink({ children, scrollToId, href, ...props }: PropTypes) {
    const searchParams = useSearchParams();


    const persistScrollFeature = () => {
        const urlScrollToId = searchParams.get("scrollToId");

        if (!urlScrollToId || scrollToId !== urlScrollToId) return; //let the Global Component Handle it

        scrollElementToView(urlScrollToId);
    }

    return (
        <Link {...props}
            onClick={persistScrollFeature}
            href={`${href}?scrollToId=${scrollToId}`}
            scroll={false} //very important, its disable nextJs scroll To top on navigation feature
        >
            {children}
        </Link>
    )
}

export default ScrollToLink

现在,在任何组件中,您都可以像这样导入和使用 ScrollToLink。

<ScrollToLink href="/" scrollToId='hero-section'>Hero Section</ScrollToLink> 
<ScrollToLink href="/" scrollToId='Testimony-section'>Hero Section</ScrollToLink> 

<div id='hero-section'>I am Hero Section</div>
<div id='Testimony-section'>I am Hero Section</div>


//You can offset the scrollToView position like this
<div id='Testimony-section' data-scroll-to-view-offset='-200'>I am Hero Section</div>

-1
投票

<style global jsx>
   {`
       html {
          scroll-behavior: smooth;
        }
  `}
  </style>

© www.soinside.com 2019 - 2024. All rights reserved.