CSS-HTML动画延迟失效:谷歌加载蛇形效果无法实现
问题
我正在尝试制作谷歌风格的加载动画,想通过animation-delay属性实现蛇形弹跳效果,但这个属性完全不生效。试过加-webkit前缀、用负值延迟都没用,HTML结构没问题,这是怎么回事?
原因分析
问题出在CSS选择器优先级上:.dots-container .d是后代选择器(优先级权重:0,0,2,0),而.dot1这类单个类选择器的权重是0,0,1,0。前者优先级更高,导致你在.dot1等类里写的animation-delay被.dots-container .d里的animation声明覆盖了——因为animation是简写属性,它会重置所有未明确指定的动画相关属性,包括animation-delay。
修复方案
有两种简单的修复方式:
方式一:提高选择器优先级
把.dot1这类选择器改成和.dots-container .d同级别或更高的优先级,比如:
.dots-container .d.dot1 { background-color: yellow; animation-delay: 0.3s; } .dots-container .d.dot2 { background-color: purple; animation-delay: 0.6s; } .dots-container .d.dot3 { background-color: green; animation-delay: 0.7s; } .dots-container .d.dot4 { background-color: red; animation-delay: 0.8s; } .dots-container .d.dot5 { background-color: black; animation-delay: 1s; }
方式二:拆分动画属性声明
不要在.dots-container .d里用animation简写,而是拆分写单独的动画属性,只把animation-delay放到各个dot类里:
.dots-container .d{ width: 50px; height: 50px; border-radius: 50%; display: inline-block; /* 拆分动画属性,不包含delay */ animation-name: bouncyDots; animation-duration: 1s; animation-timing-function: ease-in-out; animation-iteration-count: infinite; animation-direction: alternate; } .dot1{ background-color: yellow; animation-delay: 0.3s; } /* 其他dot类保持不变 */
修改后的完整CSS示例(方式一)
*{ margin: 0; padding: 0; box-sizing: border-box; font-family: 'Poppins', sans-serif; } body{ display: flex; justify-content: center; align-items: center; height: 100vh } .dots-container{ display: flex; justify-content: space-evenly; width: 700px; height: 100px } .dots-container .d{ width: 50px; height: 50px; border-radius: 50%; display: inline-block; animation: bouncyDots 1s ease-in-out infinite alternate; } .dots-container .d.dot1{ background-color: yellow; animation-delay: 0.3s; } .dots-container .d.dot2{ background-color: purple; animation-delay: 0.6s; } .dots-container .d.dot3{ background-color: green; animation-delay: 0.7s } .dots-container .d.dot4{ background-color: red; animation-delay: 0.8s } .dots-container .d.dot5{ background-color: black; animation-delay: 1s } @keyframes bouncyDots{ to{ transform: translateY(3rem); } }
内容的提问来源于stack exchange,提问作者marsprogrammer
相关产品推荐
相关产品推荐

