程式码分享加小纪录,如果能帮到你的话就太好了
codeSandBox
透过滚动才出现的box,会淡入,当画面滚动到看不见该box,他就会在看不到的地方悄悄淡出。
如果是资讯满满的网站大概会觉得很烦,不过应该还蛮适合好看就好的单一页面(?
import { useEffect, useState, useRef } from "react";export default function ScrollingExample() { const domRef = useRef(null); const [isVisible, setVisible] = useState(false); useEffect(() => { const handleScroll = () => { if (domRef.current) { const { top, bottom } = domRef.current.getBoundingClientRect(); const isVisible = top < window.innerHeight && bottom >= 0; setVisible(isVisible); } }; // 初始化时检查一次 handleScroll(); // 滚动时侦测 window.addEventListener("scroll", handleScroll); // 清理函数 return () => { window.removeEventListener("scroll", handleScroll); }; }, []); return { domRef, fadeInOut: { transition: "opacity .6s ease-in-out", opacity: isVisible ? 1 : 0, }, };}
// 汇入ScrollingExampleconst Container = ({ title }) => { const { domRef, fadeInOut } = ScrollingExample(); return ( <div ref={domRef} style={{ ...fadeInOut, height: "500px", backgroundColor: "black", color: "white", padding: "50px", marginBottom: "100px", fontSize: "2em", }} > {title} </div> );}function ScrollTest() { return ( <div> <Container title="box 1" /> <Container title="box 2" /> <Container title="box 3" /> <Container title="box 4" /> <Container title="box 5" /> </div> );}export default ScrollTest;