Scrolling with animation
I need to execute the javascript method开发者_如何转开发 scrollTo(x, y) with animation. I cant' use jQuery to do it.
[Working demo]
function interpolate( source,target,pos ) {
return ( source + (target - source) * pos );
}
function easing( pos ) {
return ( -Math.cos( pos * Math.PI ) / 2 ) + 0.5;
}
function scrollTop( duration ) {
duration = duration || 1000;
var startY = window.pageYOffset,
start = Number(new Date()),
finish = start + duration;
var interval = setInterval(function() {
var now = Number(new Date()),
pos = (now > finish) ? 1 : (now - start) / duration;
scrollTo(0, interpolate( startY, 0, easing(pos) ));
if ( now > finish )
clearInterval( interval );
}, 15);
};
You can animate (almost) anything in Javascript by using the window.setTimeout() and window.clearTimeout() calls. See http://www.w3schools.com/js/js_timing.asp
精彩评论