DIV CSS 佈局教程網

您现在的位置: DIV+CSS佈局教程網 >> 網頁腳本 >  >> CSS入門知識 >> CSS3基礎
11.3 呼叫動畫 animation-name 屬性
編輯:CSS3基礎     

一、animation-name 屬性

用 @keyframes 定義好的動畫不會自己跑起來,必須透過 animation-name 指名呼叫,它才會真正生效。

語法:

animation-name:動畫名;

說明:

animation-name 填的名稱必須與 @keyframes 定義的名稱完全一致,且區分大小寫,否則完全不會有任何動畫效果。兼容性方面,Chrome 與 Safari 需要加上 -webkit- 前綴,Firefox 則需要 -moz-。

舉例:

<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<title>CSS3 animation-name屬性</title>
<style type="text/css">
@-webkit-keyframes mycolor {
  0%{background-color:red;}
  30%{background-color:blue;}
  60%{background-color:yellow;}
  100%{background-color:green;}
}
@-webkit-keyframes mytransform {
  0%{border-radius:0;}
  50%{border-radius:50px; -webkit-transform:translateX(0);}
  100%{border-radius:50px; -webkit-transform:translateX(50px);}
}
div {
  width:100px;
  height:100px;
  background-color:red;
}
div:hover {
  -webkit-animation-name:mytransform;
  -webkit-animation-duration:5s;
  -webkit-animation-timing-function:linear;
}
</style>
</head>
<body>
<div></div>
</body>
</html>

分析:

這裡定義了 mycolor 與 mytransform 兩個動畫,但只呼叫 mytransform,因此只有它會生效,mycolor 完全沒有被觸發。這也說明 animation-name 是動畫的「開關」:定義不等於執行。

在 mytransform 中,0% 到 50% 之間 border-radius 從 0 變成 50px,接著 50% 到 100% 之間保持圓角不變,同時水平右移 50px。

可以試著把 mytransform 改成下面兩種寫法,比較差異:

方式(1):

@-webkit-keyframes mytransform {
  0%{border-radius:0;}
  50%{border-radius:50px;-webkit-transform:translateX(0);}
  100%{-webkit-transform:translateX(50px);}
}

方式(2):

@-webkit-keyframes mytransform {
  0%{border-radius:0;}
  50%{border-radius:50px;}
  100%{-webkit-transform:translateX(50px);}
}

初學者常有的疑問是:範例都把動畫掛在 :hover 上,一定要滑鼠移過才會動;如果希望頁面一打開就自動播放,該怎麼辦?

其實很簡單,把 :hover 的樣式整段搬到 div 本身即可:

div {
  width:100px;
  height:100px;
  background-color:red;
  -webkit-animation-name:mytransform;
  -webkit-animation-duration:5s;
  -webkit-animation-timing-function:linear;
}

舉例:

<!DOCTYPE html>
<html xmlns="https://www.w3.org/1999/xhtml">
<head>
<title>CSS3 animation-name屬性</title>
<style type="text/css">
@-webkit-keyframes mycolor {
  0%{background-color:red;}
  30%{background-color:blue;}
  60%{background-color:yellow;}
  100%{background-color:green;}
}
@-webkit-keyframes mytransform {
  0%{border-radius:0;}
  50%{border-radius:50px; -webkit-transform:translateX(0);}
  100%{border-radius:50px; -webkit-transform:translateX(50px);}
}
div {
  width:100px;
  height:100px;
  background-color:red;
  -webkit-animation-name:mytransform;
  -webkit-animation-duration:5s;
  -webkit-animation-timing-function:linear;
}
</style>
</head>
<body>
<div></div>
</body>
</html>

分析:

接著問題又來了:如果希望動畫在頁面載入時啟動,並且一直持續下去呢?那就需要搭配控制播放次數的 animation-iteration-count,下一節會詳細說明。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved