使用css3讓網頁元素通過樣式實現動畫效果代碼

來源:互聯網
上載者:User
使用css3可以在不使用javascript和flash的情況下讓網頁元素通過樣式實現動畫效果,讓網站更加酷炫。

css3過渡

過度動畫(trainsition)屬性就可以實現讓元素樣式的過度,trainsition支援的瀏覽器有ie10,firefox,chrome和opera。

先來看看trainsition的幾個屬性:

trainsition-property:規定應用過渡的css屬性名稱。

trainsition-duration:規定過度花費的時間。

trainsiton-timing-function:規定過度的時間曲線.

trainsition-delay:規定過渡何時開始。

先看一個簡單的過度例子,在demo.css中寫上

p{width:100px;height:100px;background:red;trainsition:width 3s,height 2s;//在這裡為了方便,將過渡屬性簡寫了,我們可以將過渡屬性簡寫為trainsition:加上上面四個屬性,可以把預設屬性省略。}p:hover{width:300px;height:200px;}

在demo.html中寫上

<!DOCTYPE html><html><head><link rel="stylesheet"  href="demo.css"/></head><body><p></p></body></html>

把滑鼠移動到紅色p塊上就可以看見紅色的塊長和寬慢慢的增加,這就是過渡的最簡單實現。

注意:過渡時間不設定的話,預設情況下為0。就是不會出現過渡的效果。

我們更經常使用的方法是通過js來添加樣式來實習各種動畫過渡,如下:

<!DOCTYPE html><html><head><script src="/jquery/jquery-1.11.1.min.js"></script><style>p{   background:red;   width:200px;   height:200px;   transition:width 2s,height 2s;}p.over{width:300px;height:300px;}</style></head> <body><p </p><script> $('p').hover(function(){  $('p').addClass('over');},  function(){    $('p').removeClass('over');});</script> </body></html>

改代碼中通過jquery在滑鼠划過時添加了over的樣式,在滑鼠離開時移除了over樣式,由於在p樣式裡設定了transition屬性,所以實現了過渡動畫。

但是上面雖然實現樣式的改變,我們可以看出該改變是從一個初狀態到末狀態的改變,局限性非常大,所以我們希望有中間狀態的轉化。這時候就要用到主要畫面格動畫(@keyframes):

其基本格式為:

@keyframes 名稱{

時間點{元素狀態}

....

如我們可以用

@frames chgground{    from{ backgroud:red;}    to{backgroud:yellow;}}

定義裡主要畫面格動畫之後還要把它綁定到一個要應用的元素中才可以,如:

p{animation:chgbackground 3s;}

我們用animation來綁定,該元素的屬性有:

p就有了chgbackground的動畫,我們還可以使用百分比來指定主要畫面格的狀態 ,from to 就是0%和%100,如下代碼

@frames chgbackground{  0%{background:yellow;}  50%{background:red;}  100%{background:black;}  }

t通過該代碼就可以實現背景在0%到50%和50%到100%時不一樣的漸層效果。

使用animate.css只要下載animate.css並在引用該檔案,在需要的地方加上上特定的動畫類名,就可以實現各種效果,如:

<script>$('p').addClass('shake');</script>就可以輕鬆的添加元素抖動效果。

相關文章

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.