【前言:】javascript
基本上不多動畫是須要在頁面加載的時候就執行的,因此此例子是 將css3的 animation-keyframes關鍵幀動畫,在btn按鈕點擊後去追加樣式名稱,從而達到動畫開始播放的效果。css
【實現步驟:】html
1,樣式定義:box的初始模樣;java
2,樣式定義:box-round的樣式,此處綁定keyframes;jquery
3,樣式定義:關鍵幀keyframes作好動畫執行的屬性變化;css3
4,js按鈕綁定:作box樣式的追加樣式 box-round。
web
【圖示:】動畫
【代碼以下:】spa
<script language="javascript" src="http://resunnet.com/js/jquery-1.7.1.min.js"></script> <script> $(function(){ $(".btn").click(function(){ $(".box").addClass("box-round") }) }) </script>
/*關鍵幀動畫*/ @-webkit-keyframes 'box-animation' { from { background: red; color: red; border-radius: 30px; } 50% { background: blue; color: orange; border-radius: 100px; } to { background: orange; color: blue; border-radius: 30px; } } /*初始化box的模樣*/ .box{ width:200px; height:200px; line-height:200px; text-align:center; background:#F90; font-size:12px; /*調用animation屬性,從而讓按鈕在載入頁面時就具備動畫效果*/ } /*此處樣式被js所追加*/ .box-round{ -webkit-animation-name: "box-animation"; /*動畫名稱,須要跟@keyframes定義的名稱一致*/ -webkit-animation-duration: 2s;/*動畫持續的時間長*/ -webkit-animation-iteration-count: infinite;/*動畫循環播放的次數-infinite無限次 可取數值*/ } /*按鈕*/ .btn{ width:100px; height:32px; text-align:center; background:#66C; color:#fff; font-size:14px; line-height:32px;}
<div class="box">動畫變形</div> <div class="btn">按鈕</div>
【延伸問題:】code
如何作鼠標感應後動畫執行?
只須要給box 追加一個 .box:hover 樣式便可
/*關鍵幀動畫*/ @-webkit-keyframes 'box-animation' { from { background: red; color: red; border-radius: 30px; } 50% { background: blue; color: orange; border-radius: 100px; } to { background: orange; color: blue; border-radius: 30px; } } /*初始化box的模樣*/ .box{ width:200px; height:200px; line-height:200px; text-align:center; background:#F90; font-size:12px; /*調用animation屬性,從而讓按鈕在載入頁面時就具備動畫效果*/ } /*此處樣式---->爲感應後調用動畫過程*/ .box:hover{ -webkit-animation-name: "box-animation"; /*動畫名稱,須要跟@keyframes定義的名稱一致*/ -webkit-animation-duration: 2s;/*動畫持續的時間長*/ -webkit-animation-iteration-count: infinite;/*動畫循環播放的次數-infinite無限次 可取數值*/ }