通过 CSS3,我们能够创建动画,这可以在许多网页中取代动画图片、Flash 动画以及 JavaScript
Internet Explorer 10、Firefox 以及 Opera 支持 @keyframes 规则和 animation 属性。
Chrome 和 Safari 需要前缀 -webkit-
下面是一个简单的例子,就是把图片的颜色从红色变为黄色
<style> div { width:100px; height:100px; background:red; animation:myfirst 5s; -moz-animation:myfirst 5s; /* Firefox */ -webkit-animation:myfirst 5s; /* Safari and Chrome */ -o-animation:myfirst 5s; /* Opera */ } @keyframes myfirst { from {background:red;} to {background:yellow;} } @-moz-keyframes myfirst /* Firefox */ { from {background:red;} to {background:yellow;} } @-webkit-keyframes myfirst /* Safari and Chrome */ { from {background:red;} to {background:yellow;} } @-o-keyframes myfirst /* Opera */ { from {background:red;} to {background:yellow;} } </style> </head> <body> <div></div> <p><b>注释:</b>本例在 Internet Explorer 中无效。</p>
注意:上面设置时长用的是animation,考虑到浏览器的兼容性,所以animation需要前缀
下面是一个可以动的示例:当动画为 25% 及 50% 时改变背景色,然后当动画 100% 完成时再次改变:
div { 100px; height:100px; background:red; position:relative; animation:myfirst 5s; -moz-animation:myfirst 5s; /* Firefox */ -webkit-animation:myfirst 5s; /* Safari and Chrome */ -o-animation:myfirst 5s; /* Opera */ } @keyframes myfirst { 0% {background:red; left:0px; top:0px;} 25% {background:yellow; left:200px; top:0px;} 50% {background:blue; left:200px; top:200px;} 75% {background:green; left:0px; top:200px;} 100% {background:red; left:0px; top:0px;} } @-moz-keyframes myfirst /* Firefox */ { 0% {background:red; left:0px; top:0px;} 25% {background:yellow; left:200px; top:0px;} 50% {background:blue; left:200px; top:200px;} 75% {background:green; left:0px; top:200px;} 100% {background:red; left:0px; top:0px;} } @-webkit-keyframes myfirst /* Safari and Chrome */ { 0% {background:red; left:0px; top:0px;} 25% {background:yellow; left:200px; top:0px;} 50% {background:blue; left:200px; top:200px;} 75% {background:green; left:0px; top:200px;} 100% {background:red; left:0px; top:0px;} } @-o-keyframes myfirst /* Opera */ { 0% {background:red; left:0px; top:0px;} 25% {background:yellow; left:200px; top:0px;} 50% {background:blue; left:200px; top:200px;} 75% {background:green; left:0px; top:200px;} 100% {background:red; left:0px; top:0px;} } <p><b>注释:</b>本例在 Internet Explorer 中无效。</p>
小div会从开始位置往左移动 然后往下移动 往右移动 最后回到原点