微信小程式可實時改變轉速的css3旋轉動畫
先上效果圖

LcFireRabbit
最上面那一行就是個簡單的換顏色效果,極其簡答就不多說了,直接上程式碼。
WXML
<view class='box' style='background-color:{{backgroundcolor}}'> </view> <view class='viewBox'> <button bindtap='changeColor' data-color='black' class='box'>黑</button> <button bindtap='changeColor' data-color='violet' class='box'>紫</button> <button bindtap='changeColor' data-color='orange' class='box'>橙</button> <button bindtap='changeColor' data-color='blue' class='box'>藍</button> <button bindtap='changeColor' data-color='green' class='box'>綠</button> </view>
JS
data: { backgroundcolor:'red' }, changeColor:function(e){ this.setData({ backgroundcolor: e.currentTarget.dataset.color }) }
那麼下面咱們說一說這個旋轉的動畫。小程式裡呢,有自己的動畫api,但是用起來感覺極其麻煩,而且容易產生倒轉,對裝置的效能消耗也多,動畫多了以後就會極其卡頓,所以還是css3的動畫比較好。
首先來寫這個css3動畫
css3旋轉動畫
<view class='animationSlow'></view>
.animationSlow { width: 100rpx; height: 100rpx; background-color: orange; animation-name: myfirst; /*動畫的名稱 */ animation-duration: 2000ms; /*動畫從開始到結束的時間*/ animation-timing-function: linear; /*動畫執行快慢的引數*/ animation-iteration-count: infinite; /*動畫執行多少次的引數*//*以下是相容ios所需,引數意義與上相同*/ -webkit-animation-name: myfirst; -webkit-animation-duration: 2000ms; -webkit-animation-timing-function: linear; -webkit-animation-iteration-count: infinite; } @keyframes myfirst { /*開始轉的角度*/ from { transform: rotate(0deg); }/*結束的角度*/ to { transform: rotate(360deg); } } /*相容ios*/ @-webkit-keyframes myfirst { from { transform: rotate(0deg); } to { transform: rotate(360deg); } }

效果圖
如果只是一個一次性的動畫效果,現在這些程式碼就OK了。
如果想要實時可以改變旋轉的轉速,我們還得再加點東西。
實現可以實時修改轉速
微信小程式裡涉及到實時資料就避免不了Page.data這個東西。
1.我們需要將控制動畫時間的css屬性放到內聯樣式中去
<view class='animationSlow' style='animation-duration: 2000ms;-webkit-animation-duration: 2000ms;'></view>
2.在頁面對應的js中,設定掌控時間的Page.data屬性,將wxml裡內聯屬性的時間改為Page.data的屬性。
data: { animationTime:'2000ms' },
<view class='animationSlow' style='animation-duration: {{animationTime}};-webkit-animation-duration: {{animationTime}};'></view>
3.接下來我們寫幾個按鈕,繫結上修改這個時間的方法,進而來改變轉速。這一步都是基本程式碼,我就不貼程式碼了。放個效果圖吧。

效果圖
那麼接下來重點來了:其實這裡有個bug,這個效果呢在安卓機上是一點點問題都沒有的。但是在蘋果機上,動畫一旦開始,再通過這個方法去修改轉速,就不能生效了。
解決IOS系統的BUG
上面說了,IOS系統上呢,動畫一旦開始,這個方法就不能用了。那麼咱是不是可以先把這個動畫停下來,然後再改轉速呢?這個辦法可不可以呢?答案是肯定的,但是不是去把動畫時間改為0,而是採用了css3動畫的一個屬性。 ofollow,noindex">CSS3 動畫教程
animation-play-state: paused|running;
簡而言之就是先用這個屬性把動畫暫停,修改轉速,然後再讓它跑起來。這一切都得再js裡進行。
1.需要在標籤的內聯樣式里加上這個屬性,在Page.data裡再定義一個屬性控制開始暫停。
<view class='animationSlow' style='animation-duration: {{animationTime}};-webkit-animation-duration: {{animationTime}};animation-play-state:{{status}};-webkit-animation-play-state:{{status}};'></view>
data: { animationTime:'2000ms', status: 'running'//paused },
2.然後我們去修改改變轉速的方法。暫停>(修改>跑起來),效果上稍微有些延遲。
changeTime:function(e){ this.setData({ status: 'paused' }) this.setData({ timeAnimation: e.currentTarget.dataset.time, status: 'running' }) },
3.來上效果圖了。

效果圖
可能動圖上感覺不出來,不過你們可以去真機試一下,就可以展現出來了。