CSS3提供兩種方式來實現動畫,transition與animation。animation涉及自定義一種為“@keyframes”的東西,這個需要動用到insertRule太復雜了,因此本文跳過它。有人它為transform也算一種,但它是靜態的,需要結合transition才能變成動態,因此也跳過。
transition主要就是以下四個屬性,后面跟著的是它們的初始值
transition-property: all;
transition-duration: 0s;
transition-timing-function: ease;
transition-delay: 0s;
transition-property的值可以為none,all,或指定上的屬性名
當前可進行補間的CSS屬性(比MDC上的少,去掉許多私有屬性與比較罕見的屬性)
transition-duration,動畫的持續時間,其值為一個帶單位的數值,單位可以為s與ms
transition-delay:動畫延遲多久開始.
transition-timing-function:緩動公式,值為ease | linear | ease-in | ease-out | ease-in-out | cubic-bezier(, , , )
ease
This keyword sets the easing function to cubic-bezier(0.25, 0.1, 0.25, 1.0).
linear
This keyword sets the easing function to cubic-bezier(0.0, 0.0, 1.0, 1.0).
ease-in
This keyword sets the easing function to cubic-bezier(0.42, 0.0, 1.0, 1.0).
ease-out
This keyword sets the easing function to cubic-bezier(0.0, 0.0, 0.58, 1.0).
ease-in-out
This keyword sets the easing function to cubic-bezier(0.42, 0.0, 0.58, 1.0).
cubic-bezier
Specifies a cubic bezier curve to use as the easing function. The four number values specify the P1 and P2 points of the curve as (x1, y1, x2, y2). All values must be in the range [0.0, 1.0] inclusive.
但在JS操作它們時我們其中只需要transition就行了,由于這是瀏覽器商首先搞出來,因此都帶著它們的前綴,如-ms-,-moz-等等,我們需要把它們改成駝峰風格才能調用,見下面的例子。
示例1,通過JS來操作這些CSS3屬性實現動畫效果:
- <!DOCTYPE html>
- <html>
- <head>
- <meta charset="utf-8">
- <title>dom Framework</title>
- <script>
- var dom = function(s){
- return document.getElementById(s)
- }
- dom.cssName = function (name){
- var prefixes = ['', '-ms-','-moz-', '-webkit-', '-khtml-', '-o-'],
- rcap = /-([a-z])/g,capfn = function($0,$1){
- return $1.toUpperCase();
- };
- dom.cssName = function(name, target, test){
- target = target || document.documentElement.style;
- for (var i=0, l=prefixes.length; i < l; i++) {
- test = (prefixes[i] + name).replace(rcap,capfn);
- if(test in target){
- return test;
- }
- }
- return null;
- }
- return dom.cssName(name);
- }
- window.onload = function(){
- var el = dom("test"),
- css3transition = dom.cssName("transition");
- el.style[css3transition] = "all 5s ease-in"
- dom("start").onclick = function(){
- el.style.width = "400px";
- }
- }
- </script>
- <style>
- #test{
- background: red;
- width:10px;
- height:30px;
- }
- </style>
- </head>
- <body>
- <h3>CSS3 動畫 by 司徒正美</h3>
- <div id="test">
- TEXT
- </div>
- <button id="start" type="button">開始測試</button>
- </body>
- </html>
新聞熱點
疑難解答