css3中的transform、transition、translate、animation(@keyframes)的區別


一、前言

  在CSS中,我們經常會使用到transform、transition、translate、animation(@keyframes)這些長得相似,又不好區分的屬性(值)。每當需要使用它們,都需要去查找相關的介紹和使用方法,完成后卻又繼續困惑中。而本篇博客將將它們匯合起來,一起介紹給你。

  簡單介紹:

  • transform屬性:向元素應用 2D 或 3D 轉換。該屬性允許我們對元素進行旋轉、縮放、移動或傾斜
    例如:transform:rotate(7deg); transform:translate(x,y);。

  • translate屬性值:是transform的值,定義 2D 轉換,表示對當前元素的位移
    和rotate(angle)旋轉,scale(x,y)縮放等並列 ,同為transform的值。

  • transition屬性:允許CSS屬性值在一定的時間區間內平滑的過渡,需要事件的觸發,例如單擊、獲取焦點、失去焦點等
    例如:transition(border-radius  2s); 表示在兩秒時間內過渡border-radius屬性的變化狀態

  • animation屬性:通過幀動畫對當前元素的某些屬性進行幀動畫的播放,功能相似於transition,但更加的精確、可控
    例如:animation:mymove 5s infinite;(mymove是幀動畫的名稱)

  • translation:意思是翻譯,在CSS中沒有任何應用,不過它容易和上面的混淆。。。

二、正文

1.transform介紹

  • 旋轉:rotate() 順時針旋轉給定的角度,允許負值 rotate(30deg) 
  • 扭曲:skew() 元素翻轉給定的角度,根據給定的水平線(X 軸)和垂直線(Y 軸)參數:skew(50deg,20deg) 
  • 縮放:scale() 放大或縮小,根據給定的寬度(X 軸)和高度(Y 軸)參數: scale(2,4) 
  • 移動:translate() 平移,傳進 x,y值,代表沿x軸和y軸平移的距離
div{ margin:30px; width:200px; height:100px; background-color:yellow;
/* Rotate div */ transform:rotate(9deg); -ms-transform:rotate(9deg); /* Internet Explorer 9*/ -moz-transform:rotate(9deg); /* Firefox */ -webkit-transform:rotate(9deg); /* Safari 和 Chrome */ -o-transform:rotate(9deg); /* Opera */
}

上面的代碼表示:對元素旋轉了9度,還可以進行其他的轉換scale的縮放和translate的位移。

 

2.translate介紹:

translate(x, y)只是transform的一部分,主管位移功能。

還有:translate3d(x, y, z)和translateX(x)、translateY(y)、translateZ(z)。

 

3.transition介紹

transition屬性是個復合屬性,她包括以下幾個子屬性:

  • transition-property :規定設置過渡效果的css屬性名稱
  • transition-duration :規定完成過渡效果需要多少秒或毫秒
  • transition-timing-function :指定過渡函數,規定速度效果的速度曲線
  • transition-delay :指定開始出現的延遲時間

默認值分別為:all 0 ease 0 

div{ width:100px; height:100px; background:blue; transition:width 2s; -moz-transition:width 2s; /* Firefox 4 */ -webkit-transition:width 2s; /* Safari and Chrome */ -o-transition:width 2s; /* Opera */
} div:hover{ width:300px; /* 也可以對顏色進行過渡,比如background: red;*/
}

上面的代碼表示:在2s內對元素進行寬度從100px到300px的變化過渡;

注意:CSS屬性值在一定的時間區間內平滑的過渡,需要事件的觸發,例如單擊、獲取焦點、失去焦點等

https://www.cnblogs.com/afighter/p/5731293.html

 

4. animation和@keyframes關鍵幀的介紹

animation屬性是個復合屬性,她包括以下幾個子屬性:

  • animation-name 規定需要綁定到選擇器的 keyframe 名稱。。 
  • animation-duration 規定完成動畫所花費的時間,以秒或毫秒計。 
  • animation-timing-function 規定動畫的速度曲線。 
  • animation-delay 規定在動畫開始之前的延遲。 
  • animation-iteration-count 規定動畫應該播放的次數。 
  • animation-direction 規定是否應該輪流反向播放動畫。
div{ width:100px; height:100px; background:red; position:relative; animation:move 5s infinite; -webkit-animation:mymove 5s infinite; /*Safari and Chrome*/
} @keyframes move{ from {top:0px;} to {top:200px;} }

上面的代碼表示:在5s內對元素的相對位置的top屬性進行從0px到200px的移動。

 

transition和animation的區別:

  • animation可以控制到每一幀,
    高版本的瀏覽器還支持css或者JS控制停止動畫 以及獲取動畫當前狀態等;
  • translation只是一個過渡 只能設置 初始值和結束值。

三、結語

先到這兒嘍!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM