關於CSS3元素中過渡屬性transition的詳細介紹

來源:互聯網
上載者:User

過渡動畫是動畫的基礎

在學習動畫屬性之前
我們需要先瞭解過渡屬性transition

過渡transition

先來看一個小例子

<p class="demo"></p>
.demo {    width: 100px;    height: 100px;    background-color: royalblue;}.demo:hover {    width: 200px;}

這樣當我的游標懸浮在demo的一瞬間
它的寬度變成了200px

有沒有辦法讓我們游標懸浮在元素時,元素寬度緩慢變寬呢
在CSS3之前我們只能使用麻煩的js指令碼
但是現在我們只需要添加一個屬性
就可以達到我們的目的

.demo {    width: 100px;    height: 100px;    background-color: royalblue;    transition: width 1s; /*增*/}.demo:hover {    width: 200px;}

transition它的作用就是指定當你的元素某些樣式發生變化時
這些樣式可以漸漸過渡到最終屬性值

它是一個複合屬性
有以下子屬性

  • transition-property:指定過渡或動態類比的css屬性

  • transition-duration:指定過渡所需要的時間

  • transition-timing-function:指定過渡函數

  • transition-delay:指定開始出現的延遲時間

transition-property 我們想要哪種屬性過渡就寫哪種屬性
或者乾脆寫過渡所有屬性的關鍵字all

transition-duration漸層時間屬性值就是“數字+s”
代表幾秒鐘內過渡

transition-timing-function 是可選的屬性值,有如下可選值

  • linear
    線性過渡,等價貝茲路徑(0.0, 0.0, 1.0, 1.0)

  • ease(預設)
    平滑過渡,等價貝茲路徑(0.25, 0.1, 0.25, 1.0)

  • ease-in
    由慢到快,等價貝茲路徑(0.42, 0, 1.0, 1.0)

  • ease-out
    由快到慢,等價貝茲路徑(0, 0, 0.58, 1.0)

  • ease-in-out
    由慢到快再到慢,等價貝茲路徑(0.42, 0, 0.58, 1.0)

  • step-start
    等同 steps(1, start)

  • step-end
    等同 steps(1, end)

  • steps():
    兩個參數的步進函數。第一個參數為正整數,指定函數步數。第二個參數取值是start或end,指定每一步的值發生變化的時間點。第二個參數可選,預設值為end。

  • cubic-bezier(num, num, num, num):
    特定的貝茲路徑類型,4個數值需在[0, 1]區間內

大多我們都用不上,最常用的大概就是我們預設的ease和線性過渡linear了

transition-delay 同樣是可選屬性值
如果你想要延遲過渡,換句話說如果我們想要在過渡前停一小會兒
那麼就在這個複合屬性的最後添加我們需要延遲的時間“數字+s”

這個屬性可以對多個不同的屬性進行設定
我們要做的就是使用逗號隔開

.demo {    width: 100px;    height: 100px;    background-color: royalblue;    transition: width 1s linear,                 height 1s linear,                background-color 2s 1s; /*改*/}.demo:hover {    width: 200px;    height: 200px;    background-color: lawngreen; /*改*/}

滑鼠移出元素後,元素又過渡回來

使用過渡屬性而不是指令碼的另一個原因是
指令碼方法改變多個元素樣式可能會產生衝突
解決的辦法是使用bool變數加鎖,還是很麻煩
我們的transition過渡屬性就不需要考慮這麼多
元素與元素之間互不影響

還有一點要注意,元素過渡需要知道樣式具體的起始屬性和末尾屬性
比如說我們例子中的width明確了從100px過渡到200px

.demo:hover {    width: auto; /*改*/    height: 200px;    background-color: lawngreen; /*改*/}

改變了懸浮樣式width為auto
我們發現當游標懸浮元素後
width屬性並沒有發生過渡

參與過渡的屬性

當然也不是所有的樣式都可以過渡
比如說你想讓 display:block 過渡到 display:inline-block
那是不可能的
有以下屬性參與過渡

  • color

  • visibility

  • opacity

  • vertical-align

  • z-index

  • clip

  • width/height

  • top/bottom/left/right

  • background-color/position

  • border-top/bottom/left/right-color/width

  • border/letter/word-spacing

  • font-size/weight

  • line-height

  • margin/padding-top/bottom/left/right

  • max/min-height/width

  • outline-color/width

  • text-indent/shadow

可以看到這個屬性真的是十分強大

相關文章

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.