1.transition過渡
可以為一個元素在不同狀態之間進行切換時添加過渡效果,實現不同狀態間的變化效果。通過觸發事件(鼠標懸停、點擊等),在兩個狀態間切換。
1.1 使用
語法:transition: [property] [duration] [timing-function] [delay];
property??:過渡屬性(如
background-color
,all
表示所有屬性)。??duration??:持續時間(如
0.3s
),必須設置。??timing-function??:速度曲線(
ease
、linear
、cubic-bezier()
等)。??delay??:延遲時間(如
0.2s
)
示例代碼:表示當鼠標懸停在img標簽時,寬高從200×200變為500×400。
<style>img {width:200px;height:200px;transition:all 1s;/*all表示對自身所有屬性都加上過渡效果,若要單獨讓某個屬性添加過渡則寫具體的css屬性,1s表示過渡效果的時間*/}img:hover {width:500px;height:400px;}
</style><img src="#">
2. animation動畫
通過關鍵幀定義復雜動畫序列,支持自動播放和循環,允許在復數個狀態間進行切換,且可以在頁面加載時自動開始運行,不需要事件觸發。
2.1 使用
語法:animation: [name] [duration] [timing-function] [delay] [iteration-count] [direction] [fill-mode];
??name??:
@keyframes
定義的動畫名。??iteration-count??:播放次數(
infinite
為無限循環)。??direction??:播放方向(
alternate
交替播放)。??fill-mode??:動畫結束狀態(
forwards
保留最后一幀)。
代碼示例:修改box盒子的background-color屬性,從紅色變為黃色。
<style>@keyframes example {/* from(等價于 0%):動畫起始狀態;to(等價于 100%):動畫結束狀態,可通過百分比定義中間狀態(如 50% {background-color: blue;} */from {background-color: red;}to {background-color: yellow;}
}.box {width: 100px;height: 100px;background-color: red;/* 引用關鍵幀,過渡時間為5s, infinite為動畫無限循環 */animation: example 5s infinite;
}
</style>