在 @keyframes 中创建动画时,请把它捆绑到某个选择器,否则不会产生动画效果。
通过规定至少以下两项 CSS3 动画属性,即可将动画绑定到选择器:
- 规定动画的名称
- 规定动画的时长
实例
把 "myfirst" 动画捆绑到 div 元素,时长:5 秒:
div { animation: myfirst 5s; -moz-animation: myfirst 5s; /* Firefox */ -webkit-animation: myfirst 5s; /* Safari 和 Chrome */ -o-animation: myfirst 5s; /* Opera */ }
当动画为 25% 及 50% 时改变背景色,然后当动画 100% 完成时再次改变:
@keyframes myfirst { 0% {background: red;} 25% {background: yellow;} 50% {background: blue;} 100% {background: green;} } @-moz-keyframes myfirst /* Firefox */ { 0% {background: red;} 25% {background: yellow;} 50% {background: blue;} 100% {background: green;} } @-webkit-keyframes myfirst /* Safari 和 Chrome */ { 0% {background: red;} 25% {background: yellow;} 50% {background: blue;} 100% {background: green;} } @-o-keyframes myfirst /* Opera */ { 0% {background: red;} 25% {background: yellow;} 50% {background: blue;} 100% {background: green;} }
简写的动画 animation 属性:
div { animation: myfirst 5s linear 2s infinite alternate; /* Firefox: */ -moz-animation: myfirst 5s linear 2s infinite alternate; /* Safari 和 Chrome: */ -webkit-animation: myfirst 5s linear 2s infinite alternate; /* Opera: */ -o-animation: myfirst 5s linear 2s infinite alternate; }