今天來給大家分享一下CSS3 @keyframes 規則!
在你了解CSS3 @keyframes 規則時我先來給大家說說什么是css3中的動畫
動畫是使元素從一種樣式逐漸變化為另一種樣式的效果。
您可以改變任意多的樣式任意多的次數。
請用百分比來規定變化發生的時間,或用關鍵詞 "from" 和 "to",等同於 0% 和 100%。
0% 是動畫的開始,100% 是動畫的完成。
為了得到最佳的瀏覽器支持,您應該始終定義 0% 和 100% 選擇器。
當您在 @keyframes 中創建動畫時,請把它捆綁到某個選擇器,否則不會產生動畫效果。
通過規定至少以下兩項 CSS3 動畫屬性,即可將動畫綁定到選擇器:
- 規定動畫的名稱
- 規定動畫的時長
注釋:您必須定義動畫的名稱和時長。如果忽略時長,則動畫不會允許,因為默認值是 0。
實例
1.當動畫為 25% 及 50% 時改變背景色,然后當動畫 100% 完成時再次改變:
HTML:
<div></div>
CSS:
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
{
0% {background:red;}
25% {background:yellow;}
50% {background:blue;}
100% {background:green;}
}
2.這個例子是讓一個正方形上下樓梯的一個動畫效果,有興趣的可以試試哦!
html:
<div id="box">
<div id="div1"></div>
<div id="div2"></div>
<div id="div3"></div>
<div id="div4"></div>
</div>
CSS:
#box{
position: relative;
width: 600px;
height: 600px;
background: black;
}
#div1{
position: absolute;
width: 50px;
height: 50px;
background: red;
right: 150px;
bottom: 0;
animation:yd 10s linear infinite alternate;
}
@keyframes yd {
0%{
transform: translate(0)
}
16%{
transform: translateY(-50px);
}
32%{
transform: translateY(-50px) translateX(50px);
}
48%{
transform: translateY(-100px) translateX(50px);
}
65%{
transform: translateY(-100px) translateX(100px);
}
82% {
transform: translateY(-150px) translateX(100px);
}
100%{
transform: translateY(-150px) translateX(150px);
}
}
#div2{
bottom: 0;
right: 0;
position: absolute;
width: 150px;
height: 50px;
background: yellow;
}
#div3{
bottom: 50px;
right: 0;
position: absolute;
width: 100px;
height: 50px;gei
background: yellow;
}
#div4{
bottom: 100px;
right: 0;
position: absolute;
width: 50px;
height: 50px;
background: yellow;
}
在此我還給大家列出了 @keyframes 規則和所有動畫屬性:
屬性 | 描述 | CSS |
---|---|---|
@keyframes | 規定動畫。 | 3 |
animation | 所有動畫屬性的簡寫屬性,除了 animation-play-state 屬性。 | 3 |
animation-name | 規定 @keyframes 動畫的名稱。 | 3 |
animation-duration | 規定動畫完成一個周期所花費的秒或毫秒。默認是 0。 | 3 |
animation-timing-function | 規定動畫的速度曲線。默認是 "ease"。 | 3 |
animation-delay | 規定動畫何時開始。默認是 0。 | 3 |
animation-iteration-count | 規定動畫被播放的次數。默認是 1。 | 3 |
animation-direction | 規定動畫是否在下一周期逆向地播放。默認是 "normal"。 | 3 |
animation-play-state | 規定動畫是否正在運行或暫停。默認是 "running"。 | 3 |
animation-fill-mode | 規定對象動畫時間之外的狀態。 | 3 |
想要了解更多快來多多關注我!