css3新增属性@keyframes(关键帧),可以帮助开发者不必依赖JavaScript,只使用css代码完成动画制作。@keyframes创建动画的原理是:将一套 CSS 样式逐渐变化为另一套样式,在动画过程中,可以多次改变这套 CSS 样式,以百分比来规定改变发生的时间,或者通过关键词 "from" 和 "to",等价于 0% 和 100%。注意,@keyframes的兼容性如下:目前浏览器都不支持 @keyframes 规则Firefox 支持替代的 @-moz-keyframes 规则Opera 支持替代的 @-o-keyframes 规则Safari 和 Chrome 支持替代的 @-webkit-keyframes 规则
工具/原料
网页编辑器
浏览器
@keyframes制作动画
1、@keyframes的基本语法:@keyframes animationname {keyframes-selector {css-styles;}}其中:animationname:动画名称keyframes-selector:动画时长的百分比css-styles:CSS 样式属性例子:css部分:.div1{ position: relative; width:100px; height:100px; background: darkslategray animation:myfirst 5s infinite; -webkit-animation:myfirst 5s infinite; -moz-animation:myfirst 5s infinite; -o-animation:myfirst 5s infinite; } @keyframes myfirst{ 0%{left:0px;} 100%{left:300px;} }html部分:<div class="div1">keyframes动画示例</div>效果如图:
2、在一个动画中改变多个 CSS 样式例子:css部分:.div1{ position: relative; width:100px; height:100px; color:#fff; background: darkslategray; animation:myfirst 5s infinite; -webkit-animation:myfirst 5s infinite; -moz-animation:myfirst 5s infinite; -o-animation:myfirst 5s infinite; } @keyframes myfirst{ 0%{ left:0px; top: 0px; } 100%{ left:300px; top:400px; } }html部分:<div class="div1">keyframes动画示例</div>效果如图:
3、带有多个 CSS 样式的多个 keyframe 选择器例子:css部分:.div1{ position: relative; width:200px; height:200px; color:#fff; background: darkslategray; animation:myfirst 5s infinite; -webkit-animation:myfirst 5s infinite; -moz-animation:myfirst 5s infinite; -o-animation:myfirst 5s infinite; } @keyframes myfirst{ 0%{ left:0px; top: 0px; background: darkslategray; } 25%{ left:100px; top:150px; background: rosybrown; } 50%{ left: 150px; top:300px; background: red; } 75%{ left:300px; top:400px; background: goldenrod; } 100%{ left:0px; top:0px; background:darkorchid; } }html部分:<div class="div1">keyframes动画示例多个 CSS 样式的多个 keyframe 选择器</div>效果如图:
4、keyframe兼容性代码具体如下:@keyframes myfirst { from {top:0px;} to {top:200px;} } @-moz-keyframes myfirst/* Firefox */ { from {top:0px;} to {top:200px;} } @-webkit-keyframes myfirst /* Safari 和 Chrome */ { from {top:0px;} to {top:200px;} } @-o-keyframes myfirst /* Opera */ { from {top:0px;} to {top:200px;} }