next.js 如何添加自动滚动到一个页面上的下一节?

xwbd5t1u  于 2023-10-18  发布在  其他
关注(0)|答案(1)|浏览(92)

我想在用户向下或向上滚动时添加节间自动滚动,在滚动到屏幕的一半后,会自动平滑过渡到同一页面上的下一个屏幕,在滚动到该屏幕的一半后,也应该平滑过渡到下一节,等等。
页面代码:

'use client'

import Image from 'next/image'

import About from './components/About'
import Lodge from './components/Lodge'
import AboutS from './components/AboutS'
import Reviews from './components/Reviews'
import Blog_h from './components/Blog_h'
import Contacts from './components/Contacts'

export default function Home() {

  return (
    <div className="">

      <section
        id="home"
        className="bg-local bg-no-repeat bg-center bg-cover bg-test-bg w-full h-[1080px]"
      >
        <div className="font-medium lg:text-[36px] md:text-[28px] sm:text-[24px] leading-normal text-white pt-[619px] pl-[80px]">
           Enjoy your time in Lux in the clouds
        </div>

        <Image className="pt-[30px] pl-[80px]"
          src="/images/portal360.svg"
          alt="Portal 360"
          width={1154}
          height={162}
        />
      </section>

      <section id="about">
        <About />
      </section>

      <section id="lodge">
        <Lodge />
      </section>

      <section id="abouts">
        <AboutS />
      </section>

      <section id="reviews">
        <Reviews />
      </section>

      <section id="ourblog">
        <Blog_h />
      </section>

      <section id="contacts">
        <Contacts />
      </section>
      
    </div>
  )
}
vwoqyblh

vwoqyblh1#

sectionRefCallback函数用作ref回调函数,用于捕获每个section元素的引用。这确保sectionsRef.current数组始终包含对所有节的最新引用。

import React, { useEffect, useRef } from 'react';

const ScrollToNextSection = () => {
  const sectionsRef = useRef([]);
  const activeIndexRef = useRef(0);
  
  useEffect(() => {
    const sections = sectionsRef.current;
    const activeIndex = activeIndexRef.current;

    const handleScroll = () => {
      const scrollPosition = window.scrollY || window.pageYOffset;

      if (scrollPosition >= sections[activeIndex].offsetTop + sections[activeIndex].offsetHeight) {
        scrollToNextSection();
      }
    };

    const scrollToNextSection = () => {
      if (activeIndex < sections.length - 1) {
        activeIndexRef.current = activeIndex + 1;
        sections[activeIndexRef.current].scrollIntoView({ behavior: 'smooth' });
      }
    };

    window.addEventListener('scroll', handleScroll);

    return () => {
      window.removeEventListener('scroll', handleScroll);
    };
  }, []);

  const sectionRefCallback = (section) => {
    if (section && !sectionsRef.current.includes(section)) {
      sectionsRef.current.push(section);
    }
  };

  return (
    <>
      <section ref={sectionRefCallback}>Section 1</section>
      <section ref={sectionRefCallback}>Section 2</section>
      <section ref={sectionRefCallback}>Section 3</section>
    </>
  );
};

export default ScrollToNextSection;

相关问题