css的過渡transition和動畫animation
過渡
過渡(transition)是CSS3中具有顛覆性的特性之一,我們可以在不使用Flash動畫或JavaScript的情況下,當元素從一種樣式變換為另一種樣式時元素添加效果。
過渡動畫:是從一個狀態漸漸的過渡到另一個狀態。低版本瀏覽器不支援,但是不影響頁面布局。經常和:hover一起搭配使用。
屬性 | 描述 | 取值範圍 |
transition-property | 應用過渡效果的 CSS 屬性名 | CSS屬性都可以(all, width, color …) |
transition-duration | 過渡效果持續時間 | 秒和毫秒都可以, 1s 1000ms … |
transition-timing-function | 過渡效果展示方式 | linear(勻速), ease(開始慢、中間快、結束慢,默認可省略) |
transition-delay | 過渡效果延遲時間 | 秒和毫秒都可以, 1s 1000ms … |
<style>
div{
width: 200px;
height: 100px;
background-color: pink;
transition: width 1s ease 0s,height 2s ease 1s;
// transition:要過渡的屬性 花費的時間 運動曲線 何時開始;
transition-property: width;
transition-duration: 1s;
transition-timing-function: linear;
transition-delay: 2s;
/* Safari */
-webkit-transition-property: width;
-webkit-transition-duration: 1s;
-webkit-transition-timing-function: linear;
-webkit-transition-delay: 2s;
}
div:hover{
width:400px;
}
</style>
//完整程式碼塊
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>過渡</title>
</head>
<style type="text/css">
div {
float: left;
margin-right: 10px;
width: 200px;
height: 200px;
text-align: center;
line-height: 200px;
background-color: skyblue;
}
/* 滑鼠懸停時改變盒子顏色 */
div:hover {
background-color: aqua;
transition: all .8s linear 0s;
}
</style>
<body>
<div></div>
</body>
</html>
動畫
動畫(animation)是使元素從一種樣式逐漸變化為另一種樣式的效果。
您可以改變任意多的樣式任意多的次數。
請用百分比來規定變化發生的時間,或用關鍵詞 “from” 和 “to”,等同於 0% 和 100%。
0% 是動畫的開始,100% 是動畫的完成。
為了得到最佳的瀏覽器支援,您應該始終定義 0% 和 100% 選擇器。
值 | 描述 |
---|---|
animation-name | 規定需要綁定到選擇器的 keyframe 名稱。。 |
animation-duration | 規定完成動畫所花費的時間,以秒或毫秒計。 |
animation-timing-function | 規定動畫的速度曲線。 |
animation-delay | 規定在動畫開始之前的延遲。 |
animation-iteration-count | 規定動畫應該播放的次數。 |
animation-direction | 規定是否應該輪流反向播放動畫。 |
animation-play-state | 規定動畫是否正在運行或暫停。默認是 “running”。 |
animation-fill-mode | 規定對象動畫時間之外的狀態。 |
/* 動畫程式碼 */
@keyframes example {
from {background-color: red;}
to {background-color: yellow;}
}
/* 向此元素應用動畫效果 */
div {
width: 100px;
height: 100px;
background-color: red;
animation-name: example;
animation-duration: 4s;
}
// 完整程式碼塊
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>animation</title>
</head>
<style type="text/css">
div {
float: left;
margin-right: 10px;
width: 200px;
height: 200px;
text-align: center;
line-height: 200px;
background-color: skyblue;
position: absolute;
border-radius: 50%;
}
div {
animation: myfirst 5s linear 2s infinite alternate;
}
@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;}
}
</style>
<body>
<div></div>
</body>
</html>