I recently read up a bunch on requestAnimationFrame, and its promises of smoother handling of animations on scroll events. I took the approach from this article in particular: http://www.html5rocks.com/en/tutorials/speed/animations/

So I decided to try it out on a new site I'm working on, and while everything seems great in Chrome, the animation is very choppy in Firefox and IE. When I switch back to calling my update function directly from the scroll event handler, it actually ends up being MUCH smoother. So I'm baffled in that it seems like requestAnimationFrame is actually slowing things down for me.

Here's my code, maybe I'm doing something wrong? I'm just trying to update the background-position on a div when the user scrolls:

var scrollY = $(window).scrollTop();
var scrollTicking = false;

$(window).on('scroll', function(){
    scrollY = Math.max($(window).scrollTop(), 0);
    requestScrollTick();
});

function requestScrollTick(){
    if(!scrollTicking) {
        requestAnimationFrame(scrollUpdate);
    }
    scrollTicking = true;
}

function scrollUpdate(){
    scrollTicking = false;
    CT.animateFeatureCarousel(scrollY);
}


...
...


animateFeatureCarousel: function(scrollY){
    var $carousel = $('.curated-carousel');

    var scrollStart = $carousel.offset().top;
    var scrollEnd = scrollStart + $carousel.height();
    var scrollDelta = scrollEnd - scrollStart;

    var startTop = 50;
    var endTop = 90;
    var topDelta = (endTop - startTop) / scrollDelta;
    var newTop = (startTop - ((scrollY - scrollStart) * topDelta));

    $carousel.find('.curated-carousel-item.current').css({
    'background-position': 'center '+newTop+'%'
     });
}
有帮助吗?

解决方案

Requestanimationframe is an FPS timing issue. It prevents animations from dropping frames by aligning them with the browsers ability to draw the frame. I think your issue is that you want it to specifically align with the visual scroll as done by the user. Since you want the image to move exactly in time with the scroll then you want to keep using the onScroll directly. If you were instead animating a bunch of things around the screen you'd want to use requestanimationframe so that they stay aligned with the ability of the browser to update them.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top