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

Framer Motion如何仅在动画执行阶段为元素添加overflow:hidden样式

实现方案

你可以直接通过Framer Motion的transitionEnd属性实现需求,无需额外引入状态监听,修改后的代码如下:

const PanelBody = ({children, isFramed, isOpen}) => {
  const currentVariant = isOpen ? 'open' : 'closed'

  const loadFeatures = () =>
    import('./framerMotionFeatures.js').then(res => res.default)

  return (
    <LazyMotion features={loadFeatures}>
    <StyledPanelBody
      initial={currentVariant}
      animate={currentVariant}
      variants={{
        closed: {
          height: 0,
          overflow: 'hidden'
        },
        open: {
          height: 'auto',
          overflow: 'hidden',
          transitionEnd: {
            overflow: 'visible'
          }
        }
      }}
      transition={{ease: 'easeInOut', duration: 0.3}}
      isFramed={isFramed}
      isOpen={isOpen}
    >
      <div>
        {children}
      </div>
    </StyledPanelBody>
    </LazyMotion>
  )
}

逻辑说明

  • 收起状态固定设置overflow: hidden,避免内容溢出
  • 展开动画执行过程中默认生效overflow: hidden,防止动画过程中内容溢出覆盖下方元素
  • 展开动画完全结束后,通过transitionEnd配置将overflow改为visible,保证面板内部下拉列表等需要溢出展示的元素可以正常渲染
    如果需要更灵活的自定义控制,也可以配合onAnimationStart和onAnimationComplete回调,结合本地状态变量来控制样式,实现效果和上述方案一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 23:36:02