使用max-height实现的div滑入展开效果方向反向如何修复
问题原因
动画方向相反的核心原因是.container使用bottom: -46px作为绝对定位锚点:绝对定位元素锚定bottom属性时,底部位置固定,高度增加会向上延伸,高度减小会向下收缩,刚好和预期的向下展开、向上收起效果相反。
修复方案
无需修改React组件代码,仅调整CSS定位规则即可,完全保留你要求的绝对定位、margin、padding设置:
- 将
.container的定位锚点从bottom改为top,用top: 100%替代原bottom: -46px,让容器顶部锚定在父元素.App的底部,高度增加时向下延伸,符合展开方向预期。 - 闭合状态下新增上下内边距为0的规则,避免max-height为0时因padding残留空白区域。
修改后完整CSS代码如下:
.App { font-family: sans-serif; text-align: center; position: relative; } .container { position: absolute; top: 100%; right: 0; margin-right: 30px; padding: 10px 20px; background: #fff; border: 1px solid #e2e2e2; transition: all 0.3s ease-in-out; overflow: hidden; } .containerClosed { max-height: 0; padding-top: 0; padding-bottom: 0; transition: all 0.3s ease; will-change: transform; } .containerOpened { max-height: 100px; transition: all 0.3s ease; will-change: transform; } .container input { border: none; outline: none; border-bottom: 1px solid #e2e2e2; width: 200px; }
如果需要调整容器和按钮之间的间距,只需修改.container的top值即可,比如要增加2px间距就改成top: calc(100% + 2px)。
内容的提问来源于stack exchange,提问作者Zak
相关产品推荐
相关产品推荐

