滚动动画

时间:2010-11-02 22:36:19

标签: javascript animation scrollto

我需要用动画执行javascript方法scrollTo(x,y)。我不能'使用jQuery来做到这一点。

2 个答案:

答案 0 :(得分:9)

<强> [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);
};

答案 1 :(得分:2)

您可以使用window.setTimeout()和window.clearTimeout()调用在Javascript中为(几乎)动画制作动画。见http://www.w3schools.com/js/js_timing.asp