如何解决CSS中声明覆盖导致多过渡与动画失效的问题
解决CSS过渡与动画被覆盖/失效的问题
问题1:SectionA的过渡声明被覆盖
你的代码里,#sectionA重复写了两次transition属性:
transition: width 0.5s; transition: height 0.7s;
CSS中相同属性的重复声明会被最后一次的覆盖,所以只有height的过渡生效,width的过渡直接被丢弃了。
解决方法:把多个过渡规则合并到同一个transition声明中,用逗号分隔不同属性的配置:
transition: width 0.5s, height 0.7s;
问题2:SectionB的动画逻辑错误
你定义的offHover和onHover动画关键帧完全一致,这导致无论是否触发hover,动画执行后的效果没有区别;另外初始状态下#sectionB会直接执行offHover动画,而非在鼠标离开时触发恢复动作。
解决方法:
- 拆分动画逻辑:一个负责hover时的收缩,一个负责离开hover时的恢复
- 去掉初始的
animation声明,默认保持元素初始尺寸
修正后的#sectionB相关代码:
#sectionB { width: 400px; height: 400px; background-color: #5a5; /* 移除初始动画,默认显示初始尺寸 */ } #sectionB:hover { animation: shrink 0.5s ease-in-out forwards; } #sectionB:not(:hover) { animation: expand 0.5s ease-in-out forwards; } @keyframes shrink { from { width: 400px; height: 400px; } to { width: 200px; height: 300px; } } @keyframes expand { from { width: 200px; height: 300px; } to { width: 400px; height: 400px; } }
如果想简化代码,也可以利用animation-direction: reverse复用关键帧:
#sectionB { width: 400px; height: 400px; background-color: #5a5; } #sectionB:hover { animation: shrink 0.5s ease-in-out forwards; } #sectionB:not(:hover) { animation: shrink 0.5s ease-in-out reverse forwards; } @keyframes shrink { from { width: 400px; height: 400px; } to { width: 200px; height: 300px; } }
完整修正代码
<head> <style> body { display: flex; } #sectionA { width: 400px; height: 400px; background-color: #a55; transition: width 0.5s, height 0.7s; } #sectionA:hover { width: 200px; height: 300px; } #sectionB { width: 400px; height: 400px; background-color: #5a5; } #sectionB:hover { animation: shrink 0.5s ease-in-out forwards; } #sectionB:not(:hover) { animation: expand 0.5s ease-in-out forwards; } @keyframes shrink { from { width: 400px; height: 400px; } to { width: 200px; height: 300px; } } @keyframes expand { from { width: 200px; height: 300px; } to { width: 400px; height: 400px; } } </style> </head> <body> <div id="sectionA">Section A</div> <div id="sectionB">Section B</div> </body>
内容的提问来源于stack exchange,提问作者Dhaffa Ardhana
相关产品推荐
相关产品推荐

