CSS中Transform与Transition无法配合使用问题求助
问题分析与解决
你的问题是transition对transform属性不生效,但background-color这类属性正常生效,结合代码来看,主要有以下几个可能的问题及解决办法:
1. 兼容性问题:aspect-ratio未被浏览器支持
你给.switch用了aspect-ratio: 1 / 1来做正方形,但部分旧浏览器(比如IE)不支持这个属性。一旦浏览器不识别它,.switch的宽度会直接塌陷成0,此时transform: translate(135%)等于没移动,自然看不到效果。
解决办法:
直接给.switch设置宽高,替代aspect-ratio,兼容性拉满:
.switch { background-color: black; border-radius: 50%; width: 90%; /* 新增宽度设置 */ height: 90%; /* aspect-ratio: 1 / 1; 可以删掉或注释 */ position: absolute; top: 5%; left: 3%; transition: all 200ms cubic-bezier(.3, -0.77, .6, 1.72) 0ms; }
2. 动画曲线特殊导致视觉误解
你用的cubic-bezier(.3, -0.77, .6, 1.72)是带回弹效果的曲线,动画过程可能会有反向移动的视觉错觉,容易让你误以为transform没生效;另外translate(135%)的移动距离是基于.switch自身宽度的135%,如果这个数值不够大,变化也会不明显。
验证/调整办法:
- 先把曲线换成简单的
ease,确认动画是否存在:transition: all 200ms ease 0ms; - 把
translate(135%)改成translate(200%),放大移动距离,更容易观察效果。
3. 父元素高度缺失导致容器位置异常
.container用了top: 30%,但如果页面的html和body没设置高度,30%的参考高度就是内容高度,容器位置会跑偏,间接影响你观察动画。
解决办法:
给根元素设置高度:
html, body { height: 100%; margin: 0; /* 消除默认边距 */ }
修正后的完整代码
html, body { height: 100%; margin: 0; } .container { border: 4px solid red; width: 20vw; height: 10vw; border-radius: 70px; position: relative; top: 30%; left: 40%; transition: all 10ms ease-in-out 0ms; } .button { background-color: red; width: 90%; height: 80%; border-radius: 70px; position: relative; margin: auto; top: 8%; } .switch { background-color: black; border-radius: 50%; width: 90%; height: 90%; position: absolute; top: 5%; left: 3%; transition: all 200ms ease 0ms; } .container:hover .button .switch { transform: translateX(135%); background-color: rgb(59, 59, 59); }
<div class="container"> <div class="button"> <div class="switch"></div> </div> </div>
内容的提问来源于stack exchange,提问作者user20199678
相关产品推荐
相关产品推荐

