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

如何为React+CSS移动端应用导航菜单添加左侧滑入效果

问题分析与解决方案

你的导航菜单过渡动画失效主要有两个核心原因:

  1. display属性不支持CSS过渡:切换display: none/block会直接让元素显示/隐藏,跳过过渡动画流程。
  2. 过渡逻辑匹配错误:你需要左侧滑入效果,但原CSS是从右侧通过宽度变化展开,且未明确指定过渡属性。

修改后的CSS代码(Navigation.module.css)

.navigationBody {
  height: 100vh;
  width: 85vw;
  position: fixed;
  top: 0;
  left: 0;
  background-color: rgba(100, 100, 100, 0.95);
  z-index: 999;
  /* 初始状态:完全隐藏在左侧屏幕外 */
  transform: translateX(-100%);
  /* 明确指定过渡transform属性,搭配自然的缓动函数 */
  transition: transform 0.3s cubic-bezier(0.25, 0.46, 0.45, 0.94);
  will-change: transform;
}

.navigationBody.openNav {
  /* 激活状态:滑入到可视区域 */
  transform: translateX(0);
}

/* 可选:优化关闭按钮样式 */
.navigationCancel {
  position: absolute;
  top: 20px;
  right: 20px;
  font-size: 24px;
  color: #fff;
  cursor: pointer;
}

.navigationList {
  list-style: none;
  padding: 60px 20px 20px;
  margin: 0;
}

.navigationItem {
  margin-bottom: 20px;
}

.navigationItem a {
  color: #fff;
  text-decoration: none;
  font-size: 18px;
}

修改后的React组件代码

import React, { useContext } from "react";
import { Link } from "react-router-dom";
import style from "./Navigation.module.css";

// Context
import { NavContext } from "../../context/navContext";

export const Navigation = () => {
  const { nav, setNav } = useContext(NavContext);

  return (
    <div
      className={`${style.navigationBody} ${nav ? style.openNav : ""}`}
    >
      <div
        className={style.navigationCancel}
        tabIndex="0"
        onClick={() => setNav(false)}
        // 增加键盘回车交互,符合无障碍标准
        onKeyDown={(e) => e.key === 'Enter' && setNav(false)}
      >
        X
      </div>
      <ul className={style.navigationList}>
        <li className={style.navigationItem}>
          <Link to="/">Home</Link>
        </li>
        <li className={style.navigationItem}>
          <Link to="/menu">Menu</Link>
        </li>
        <li className={style.navigationItem}>
          <Link to="/gallery">Gallery</Link>
        </li>
        <li className={style.navigationItem}>
          <Link to="/contact">Contact</Link>
        </li>
        <li className={style.navigationItem}>
          <Link to="/order">Order</Link>
        </li>
      </ul>
    </div>
  );
};

关键修改说明

  1. 替代display控制显示:用transform: translateX(-100%)将菜单初始隐藏在左侧屏幕外,避免display属性破坏过渡动画。
  2. 明确过渡属性:指定过渡transform而非仅写时长,确保动画只作用于位置变化,提升性能。
  3. 优化路由跳转:将原生<a>标签替换为React Router的<Link>,符合单页应用路由规范。
  4. 无障碍优化:为关闭按钮增加键盘回车触发逻辑,适配键盘操作场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 13:10:25