web前端入門到實戰:CSS3 動畫的實現

任務

咱們最近在SeatGeek更新了咱們的「跟蹤"圖標,以匹配咱們的新iPhone應用程序。 首席設計師在PSD中建立了具備不一樣狀態的心臟圖標,並在下面建立了動畫:css

web前端入門到實戰:CSS3 動畫的實現

什麼是CSS3動畫?

在CSS中,動畫是一種讓元素逐漸改變樣式的效果。 您可使用@keyframes關鍵字建立動畫,後跟動畫的名稱。前端

@keyframes heartAnimation {
  /* Animation code goes here */
}

要使動畫跨瀏覽器兼容,您須要使用供應商前綴:web

@keyframes heartAnimation {
  /* IE 10+ */
}

@-webkit-keyframes heartAnimation {
  /* Safari 4+ */
}

@-moz-keyframes heartAnimation {
  /* Fx 5+ */
}

@-o-keyframes heartAnimation {
  /* Opera 12+ */
}
專門創建的學習Q-q-u-n ⑦⑧④-⑦⑧③-零①②  分享學習方法和須要注意的小細節,互相交流學習,不停更新最新的教程和學習技巧(從零基礎開始到WEB前端項目實戰教程,學習工具,全棧開發學習路線以及規劃)

可是,對於本文的其他部分,我將爲了空間而排除供應商前綴。瀏覽器

下一步是添加動畫效果並肯定它們什麼時候發生。 您可使用0%到100%的百分比或使用「from"和「to"關鍵字來執行此操做,只需使用起始和結束狀態的簡單動畫。 下面是將背景顏色從黃色變爲藍色,而後從黃色變爲綠色變爲藍色的示例。ide

@keyframes colorChange {
  from {background: yellow;}
  to {background: blue;}
}

@keyframes colorChange {
  0% {background: yellow;}
  50% {background: green;}
  100% {background: blue;}
}

建立關鍵幀後,您能夠將動畫稱爲CSS屬性。 例如,下面的代碼將運行colorChange動畫2次以上,持續時間爲2秒:工具

.color-animation {
  animation-name: changeColor;
  animation-iteration-count: 2;
  animation-duration: 2s;
}

/* Shorthand */
.color-animation {
  animation: changeColor 2 2s;
}

計劃動畫

在看了幾回gif以後,我意識到它是一個輕微的收縮,而後擴展到比原始尺寸略大的尺寸,而後回到原來的尺寸。學習

Heart點擊動畫

使用上面的CSS3關鍵幀和動畫語法,這裏是我用來在本頁頂部的gif中製做動畫的代碼。 它使用css變換和屬性來縮放圖像。動畫

@keyframes heartAnimation {
  0% {transform: scale(1,1)}
  20% {transform: scale(0.9,0.9)}
  50% {transform: scale(1.15,1.15)}
  80% {transform: scale(1,1)}
}

.toggle-animation {
  animation: heartAnimation 0.7s; // no iteration count is needed as the default is 1 time
}

對於圖像,我使用的是精靈,因此我還須要更改圖像的位置以得到紅色背景:this

.toggle-animation {
  background: url('../images/animation-example-sprite.png') no-repeat -320px 0;
  animation: heartAnimation 0.7s; // no iteration count is needed as the default is 1 times
}

Loading動畫

對於一個加載狀態,我讓心臟發白而且無限地脈動in-and-out。 它還縮小並縮小到原始大小,而不是像上面的heartAnimation代碼那樣在進入原始狀態以前略大於原始大小。 如下是加載狀態的代碼:url

@keyframes loading {
  0% {transform: scale(1,1) }
  50% {transform: scale(0.8,0.8) }
  100% {transform: scale(1,1) }
}

/* Notice the added 'infinite' to is used to make the animation-iteration-count */

.toggle-loading {
  background: url('../images/animation-example-sprite.png') no-repeat -160px 0; // make background white
  animation: loading 1s infinite;
  -webkit-animation: loading 1s infinite;
  -moz-animation: loading 1s infinite;
  -o-animation: loading 1s infinite;
}

查看動畫的演示

下面是我用來點擊每一個圖標時動畫的JS。 JS添加並刪除了我添加動畫屬性的類。

專門創建的學習Q-q-u-n ⑦⑧④-⑦⑧③-零①②  分享學習方法和須要注意的小細節,互相交流學習,不停更新最新的教程和學習技巧(從零基礎開始到WEB前端項目實戰教程,學習工具,全棧開發學習路線以及規劃)
$(document).ready(function(){

  $('.animation-1 .image').on('click', function(){
    $(this).toggleClass('toggle-animation');
  });

  $('.animation-2 .image').on('click', function(){
    $(this).toggleClass('toggle-animation-slow');
  });

  $('.animation-3 .image').on('click', function(){
    $(this).toggleClass('toggle-loading');
  });
});
相關文章
相關標籤/搜索