React(CRA)项目中Transition过渡动画失效问题求助
文本展开/收起的Transition过渡不生效问题修复
问题根源
- 不可过渡属性打断动画:你在
.faded-out类中切换overflow: hidden,而overflow属于CSS不可过渡属性,它的变化会直接打断元素上的其他过渡效果。 - 伪元素无过渡配置:控制渐隐效果的
::after伪元素,其样式是在.faded-out类中新增的,移除类时伪元素直接消失,没有任何过渡动画,且伪元素本身也未配置过渡规则。
修复方案
调整SASS代码,优化过渡逻辑:
.animal-container{ display: flex; flex-direction: row; flex-grow: 1; height: 100%; .article{ padding: 20px 20px 20px 0; position: relative; overflow: hidden; /* 移到默认样式,避免切换类时触发不可过渡属性 */ max-height: 2000px; transition: max-height 1s ease-in; /* 明确过渡属性,比all更高效 */ /* 伪元素基础样式,默认隐藏 */ &::after { content: ""; position: absolute; bottom: 0; left: 0; right: 0; height: 0; opacity: 0; background-image: linear-gradient(to top, white, transparent); transition: all 0.5s ease-in; /* 给伪元素单独加过渡 */ } &.faded-out{ max-height: 200px; &::after { height: 400px; /* 显示渐隐层 */ opacity: 1; } } .title{ font-size: 30px; font-weight: bold; } .description{ padding-top: 20px; font-size: 20px; pre { white-space: break-spaces; margin: initial; } } } }
可选优化(按钮切换展开/收起)
如果需要按钮支持双向切换状态,修改JSX中的按钮逻辑:
import { useState } from "react"; import "./Animal.scss"; export const Animal = ({ className }) => { const [showFullArticle, setShowFullArticle] = useState(false); return ( <div className={`${className ? className : ""}`}> <button onClick={() => { setShowFullArticle(!showFullArticle); // 切换展开/收起状态 }} > {showFullArticle ? "SHOW LESS" : "READ MORE"} </button> <div className="animal-container"> <div className={`article ${!showFullArticle ? "faded-out" : ""}`}> <div className="title">Lorem Ipsum</div> <div className="description"> <pre> Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aliquam tortor dolor, hendrerit non nunc eget, iaculis accumsan magna. a lot more text here... </pre> </div> </div> </div> </div> ); };
内容的提问来源于stack exchange,提问作者Anatoly
相关产品推荐
相关产品推荐

