<button>按钮</button> <div>element</div>
@keyframes changeColor { 0% { background-color: blue; } 100% { background-color: purple; } } button { animation: changeColor 5s infinite; } div { animation: changeColor 5s infinite; }
在chrome和edge中按钮的修改颜色动画并没有生效,而div的修改颜色动画能够生效;在firefox中两个动画都能生效;如果给button添加背景色属性,就能在edge和chrome中生效,这是为什么。
button { animation: changeColor 5s infinite; background-color: initial; //或其他任意值 }
这是因为 Button
在不同的浏览器中的样式默认值不同,表现不一致。在 Chrome 和 Edge 中,button
的默认背景色是 transparent
,而在 Firefox 中默认背景色是有颜色的。这导致在 Chrome 和 Edge 中没有背景色的 button
没有效果,而在 Firefox 中无论有没有背景色都会有动画效果。
解决方案是给 button
明确地指定背景色,这样在 Chrome 和 Edge 中就可以生效了也就是你问题中的:
button { background-color: white; }
当然,如果你想让 button 的背景色透明,你可以通过给 button 添加伪类 ::before
或 ::after
,并将动画属性添加到伪类上来实现,以此来实现你想要的动画效果。