Authored by 梁志锋

requestAnimationFrame

@@ -160,6 +160,43 @@ $header.on('touchstart', 'a', function() { @@ -160,6 +160,43 @@ $header.on('touchstart', 'a', function() {
160 $(this).removeClass('highlight'); 160 $(this).removeClass('highlight');
161 }); 161 });
162 162
  163 +var lastTime = 0;
  164 +var prefixes = 'webkit moz ms o'.split(' ');
  165 +
  166 +var requestAnimationFrame = window.requestAnimationFrame;
  167 +var cancelAnimationFrame = window.cancelAnimationFrame;
  168 +
  169 +var prefix;
  170 +
  171 +//通过遍历各浏览器前缀,来得到requestAnimationFrame和cancelAnimationFrame在当前浏览器的实现形式
  172 +for( var i = 0; i < prefixes.length; i++ ) {
  173 + if ( requestAnimationFrame && cancelAnimationFrame ) {
  174 + break;
  175 + }
  176 + prefix = prefixes[i];
  177 + requestAnimationFrame = requestAnimationFrame || window[ prefix + 'RequestAnimationFrame' ];
  178 + cancelAnimationFrame = cancelAnimationFrame || window[ prefix + 'CancelAnimationFrame' ] || window[ prefix + 'CancelRequestAnimationFrame' ];
  179 +}
  180 +
  181 +//如果当前浏览器不支持requestAnimationFrame和cancelAnimationFrame,则会退到setTimeout
  182 +if ( !requestAnimationFrame || !cancelAnimationFrame ) {
  183 + requestAnimationFrame = function( callback, element ) {
  184 + var currTime = new Date().getTime();
  185 +
  186 + //为了使setTimteout的尽可能的接近每秒60帧的效果
  187 + var timeToCall = Math.max( 0, 16 - ( currTime - lastTime ) );
  188 + var id = window.setTimeout( function() {
  189 + callback( currTime + timeToCall );
  190 + }, timeToCall );
  191 + lastTime = currTime + timeToCall;
  192 + return id;
  193 + };
  194 +
  195 + cancelAnimationFrame = function( id ) {
  196 + window.clearTimeout( id );
  197 + };
  198 +}
  199 +
163 //暴露公共接口 200 //暴露公共接口
164 window.cookie = cookie; 201 window.cookie = cookie;
165 202
@@ -172,3 +209,7 @@ window.getUid = getUid; @@ -172,3 +209,7 @@ window.getUid = getUid;
172 window.getShoppingKey = getShoppingKey; 209 window.getShoppingKey = getShoppingKey;
173 210
174 window.rePosFooter = rePosFooter; 211 window.rePosFooter = rePosFooter;
  212 +
  213 +window.requestAnimationFrame = requestAnimationFrame;
  214 +
  215 +window.cancelAnimationFrame = cancelAnimationFrame;