一直以來都是用css3來實現動畫效果,一個是性能問題,第二個是js實現總不如css3流暢,可是最近發現了一個新大陸:requestAnimationFramejavascript
requestAnimationFrame是什麼?requestAnimationFrame()
函數就是針對動畫效果的API,你能夠把它用在DOM上的風格變化或畫布動畫或WebGL中css
requestAnimationFrame有什麼好處?
瀏覽器能夠優化並行的動畫動做,更合理的從新排列動做序列,並把可以合併的動做放在一個渲染週期內完成,從而呈現出更流暢的動畫效果。好比,經過requestAnimationFrame()
,JS動畫可以和CSS動畫/變換或SVG SMIL動畫同步發生。另外,若是在一個瀏覽器標籤頁裏運行一個動畫,當這個標籤頁不可見時,瀏覽器會暫停它,這會減小CPU,內存的壓力,節省電池電量。java
封裝後的JS:判斷使用4ms
仍是16ms
的延遲,來最佳匹配60fpscss3
(function() { var lastTime = 0; var vendors = ['webkit', 'moz']; for(var x = 0; x < vendors.length && !window.requestAnimationFrame; ++x) { window.requestAnimationFrame = window[vendors[x] + 'RequestAnimationFrame']; window.cancelAnimationFrame = window[vendors[x] + 'CancelAnimationFrame'] || // name has changed in Webkit window[vendors[x] + 'CancelRequestAnimationFrame']; } if (!window.requestAnimationFrame) { window.requestAnimationFrame = function(callback, element) { var currTime = new Date().getTime(); var timeToCall = Math.max(0, 16.7 - (currTime - lastTime)); var id = window.setTimeout(function() { callback(currTime + timeToCall); }, timeToCall); lastTime = currTime + timeToCall; return id; }; } if (!window.cancelAnimationFrame) { window.cancelAnimationFrame = function(id) { clearTimeout(id); }; } }());
demo:向上滾動web
function funscroll(){ var scroll = $("#info-position").css("top"); if( scroll>-395){ scroll-=5; } $("#info-position").css("top",scroll+"px"); requestAnimationFrame(funscroll); }
各類瀏覽器對requestAnimationFrame的支持狀況瀏覽器
谷歌瀏覽器,火狐瀏覽器,IE10+都實現了這個函數,即便你的瀏覽器很古老,上面的對requestAnimationFrame封裝也能讓這個方法在IE8/9上不出錯。函數