You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React中实现基于滚动方向的头部显隐动画方案

实现滚动时头部的显示/隐藏动画

要实现滚动时头部的显示隐藏效果,需要补充滚动位置追踪和方向判断逻辑,以下是修改后的完整代码:

修改思路

  • 使用useRef保存上次滚动的位置,用来对比当前滚动方向
  • 在handleScroll函数中判断滚动方向:向下滚动时添加隐藏类,向上滚动时添加显示类
  • 给头部元素添加过渡动画,让显示/隐藏更平滑

完整代码

App.js

import React, { useEffect, useRef } from "react";
import "./styles.css";

const Header = () => {
  const navRef = useRef(null);
  // 保存上次滚动位置
  const lastScrollY = useRef(window.scrollY);

  useEffect(() => {
    const handleScroll = () => {
      const currentScrollY = window.scrollY;
      const headerElement = navRef.current;

      // 判断滚动方向:向下滚动且头部未隐藏
      if (currentScrollY > lastScrollY.current && !headerElement.classList.contains("headerhide")) {
        headerElement.classList.remove("headershow");
        headerElement.classList.add("headerhide");
      } 
      // 向上滚动且头部未显示
      else if (currentScrollY < lastScrollY.current && !headerElement.classList.contains("headershow")) {
        headerElement.classList.remove("headerhide");
        headerElement.classList.add("headershow");
      }

      // 更新上次滚动位置
      lastScrollY.current = currentScrollY;
    };

    window.addEventListener("scroll", handleScroll);

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

  return (
    <div
      style={{
        color: "white",
        padding: 20,
        backgroundColor: "green",
        position: "fixed",
        top: 0,
        left: 0,
        width: "100%",
        // 添加过渡动画
        transition: "transform 0.3s ease-in-out"
      }}
      className="headershow"
      ref={navRef}
    >
      <h1>Header</h1>
    </div>
  );
};

export default function App() {
  return (
    <>
      <Header />
      {/* 给内容添加顶部内边距,避免被固定头部遮挡 */}
      <div
        className="App"
        style={{
          height: 2000,
          paddingTop: "80px"
        }}
      >
        <h1>Hello CodeSandbox</h1>
        <h2>Start editing to see some magic happen!</h2>
      </div>
    </>
  );
}

styles.css

.headershow {
  transform: translateY(0);
}

.headerhide {
  transform: translateY(-100%);
}

关键说明

  • 固定头部:给头部添加position: fixed,确保滚动时它始终在视口顶部,否则滚动时头部会随页面一起移动,无法实现隐藏效果
  • 过渡动画:添加transition: transform 0.3s ease-in-out让头部的显示/隐藏更流畅
  • 滚动位置追踪:用lastScrollY这个ref保存上一次的滚动位置,对比当前滚动位置判断方向
  • 类名切换逻辑:根据滚动方向切换headershow和headerhide类,实现transform的变化

内容的提问来源于stack exchange,提问作者clarkf

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 18:23:14