[React][jsx] 随画面滚动淡入淡出

程式码分享加小纪录,如果能帮到你的话就太好了

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;

关于作者: 网站小编

码农网专注IT技术教程资源分享平台,学习资源下载网站,58码农网包含计算机技术、网站程序源码下载、编程技术论坛、互联网资源下载等产品服务,提供原创、优质、完整内容的专业码农交流分享平台。

热门文章