Safari中鼠标悬停过渡动画无法反向触发问题求助
解决Safari中CSS过渡反向失效的问题
在实现父元素 hover 时移动文本的过渡效果时,遇到了浏览器兼容性问题:Chrome 中过渡可以平滑反向恢复,但在 Safari 16.1 中,如果在过渡完成前移出鼠标,文本会直接跳回初始位置,无法完成反向过渡。
原始CSS代码:
.infoContainer { display: inline-block; position: absolute; transition: bottom .5s ease-in-out; -webkit-transition: bottom .5s ease-in-out; bottom: 1rem; }
.body:hover .infoContainer { bottom: calc(100% - 1.8rem - 1.3rem - 1rem); }
问题原因
Safari 在处理基于父元素百分比的calc()过渡值时存在兼容性bug:当过渡目标值是依赖父元素尺寸的动态计算值时,浏览器无法正确追踪过渡中途的状态,导致反向过渡时直接重置到初始值。
解决方案
方案1:改用transform: translateY()实现过渡(推荐)
transform的过渡由GPU加速,兼容性更强,不会触发页面重排,能彻底避免这类bug。修改代码如下:
.infoContainer { display: inline-block; position: absolute; bottom: 1rem; transition: transform .5s ease-in-out; -webkit-transition: transform .5s ease-in-out; transform: translateY(0); } .body:hover .infoContainer { /* 计算向上位移的距离,等价于原bottom的变化逻辑 */ transform: translateY(calc(-100% + 1.8rem + 1.3rem + 1rem - 1rem)); /* 若能算出固定像素值,直接使用固定值会更稳妥 */ /* transform: translateY(-150px); */ }
方案2:给父元素设置明确高度
如果必须保留bottom属性的过渡,可以给父元素.body设置明确的高度,让Safari能正确计算calc()的数值:
.body { position: relative; height: 100%; /* 或具体固定高度,比如500px */ } .infoContainer { display: inline-block; position: absolute; transition: bottom .5s ease-in-out; -webkit-transition: bottom .5s ease-in-out; bottom: 1rem; } .body:hover .infoContainer { bottom: calc(100% - 1.8rem - 1.3rem - 1rem); }
内容的提问来源于stack exchange,提问作者JonathanV
相关产品推荐
相关产品推荐

