首页 > 解决方案 > 使用 css 将转换置于打开/关闭元素

问题描述

我目前有这样的代码,单击 readmore 时会显示子组件,但我想为其添加一些过渡,使其看起来很流畅

   import { useState } from "react"
   import { Paper } from "../Paper/paper"
   import './index.css'

export const HiddenCard = (props) => {
    const [show,setShow] = useState(false)

    const handleClick = () => {
        setShow(!show)
    }

    return (
        <Paper>
            <div className="hidden-card-body">
                <p className="Hidden-card-title">
                    TITLE
                </p>
                <div className = {`hidden-card-child ${show?"show":"hide"}`} >
                    {props.children}
                </div>
                <div className="hidden-card-button" onClick={handleClick}>
              {show ? "Read Less ^" : "Read More v"}
            </div>
            </div>
        </Paper>            
    )
}

我的CSS看起来像这样

    .hidden-card-body {
     padding: 40px 32px 64px;
     display: flex;
     flex-direction: column;
     row-gap: 24px;
    }

.Hidden-card-title {
  font-weight: bold;
  font-size: 21px;
  line-height: 32px;
  margin-top: 0px;
  margin-bottom: 0px;
}

.hidden-card-child {
  transition: all 1s ease;
  transition-delay: 1s;
}

.hidden-card-child.show {
  display: block;
}

.hidden-card-child.hide {
  display: none;
}

.hidden-card-button {
  font-size: 17px;
  font-style: normal;
  font-weight: 400;
  line-height: 24px;
  letter-spacing: 0em;
  text-align: left;
  color: #a7202c;
}

因此,当内部子元素变得可见/显示时,它应该像在可折叠中一样缓慢打开。我该如何进行转换,我是否缺少某些东西?

前 后

标签: htmlcssreactjs

解决方案


我可以将 max height : 0px 关闭,然后当它打开时可以将 max-height 设置为某个值,例如 900px 和 height auto 并在最大高度上放置一个过渡将导致打开关闭,例如:关闭:

  visibility: hidden;
  max-height: 0px;
  transition: max-height 0.3s;

打开:

  visibility: visible;
  max-height: 300px;
  height: auto;
  transition: max-height 0.6s;

推荐阅读