【问题标题】:Making a slide down menu制作下拉菜单
【发布时间】:2022-02-09 05:27:48
【问题描述】:

我正在制作一个向下滑动的菜单,但它只是跳到预期的高度,没有过渡。谁能指出我正确的方向?

const Container = styled.section`
  position: relative;
  overflow: hidden;
`

const WrapperItems = styled.div`
  padding-left: 2rem;
  user-select: none;
  transition: all 1s ease-in-out;
  position: relative;
  height: 0;

  &.active {
    max-height: 100vh;
    height: auto;
  }

return (
    <Container>
      <Wrapper onClick={() => setIsOpen(!isOpen)}>
        <div className="title">{title}</div>

      </Wrapper>
      <WrapperItems className={isOpen ? "active" : ""}>
        {items.map(item => (
          <div className="item" onClick={() => navigate(item.to)}>{item.title}</div>
        ))}
      </WrapperItems>
    </Container>
  );

【问题讨论】:

    标签: css reactjs


    【解决方案1】:

    CSS 解决方案

    不幸的是,没有办法在 CSS 中对 auto 值进行转换。做出这个选择是因为它被认为太贵了。

    如果您将auto 替换为500px 之类的固定值,它将起作用。

    为避免完全修复内容,您还可以通过在max-height 上进行转换来使用“hack”,并选择将动画设置为您知道始终高于内容价值的值。 但是您必须选择一个足够高但又不能太高的值,因为动画将开始折叠项目包装器的不可见部分会有延迟。

    padding-left: 2rem;
    user-select: none;
    transition: all 1s ease-in-out;
    position: relative;
    max-height: 0;
    
    &.active {
      max-height: 30vh; /* you know for sure that your content will never exceed 30 vh*/
    }
    

    JavaScript 解决方案

    您还拥有运行良好的基于​​ JavaScript 的解决方案。

    这是一个带有framer motion 的示例,可让您使用height: auto 语法:

    import { motion } from "framer-motion";
    
    // [...]
    
    return (
      <Container>
        <Wrapper onClick={() => setIsOpen(!isOpen)}>
          <div className="title">{title}</div>
        </Wrapper>
        <WrapperItems>
          <motion.div
            animate={isOpen ? "open" : "closed"}
            variants={{
              open: { height: "auto" },
              closed: { height: 0 },
            }}
          >
            {items.map((item) => (
              <div className="item" onClick={() => navigate(item.to)}>
                {item.title}
              </div>
            ))}
          </motion.div>
        </WrapperItems>
      </Container>
    );
    
    // [...]
    
    

    【讨论】:

      猜你喜欢
      • 2013-04-20
      • 2010-12-31
      • 1970-01-01
      • 2012-11-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多