jQuery Animating Elements by Scrolling the page

前端 未结 2 676
南方客
南方客 2021-01-03 11:28

I\'m trying to create a animation by scrolling the page, something like this:

$(function() {
$(document).on(\'scroll\', function() {
    var top = $(document         


        
相关标签:
2条回答
  • 2021-01-03 11:55

    You can simplify the whole thing with a little math. Only fire your animations whenever your range changes. Otherwise you will stop and start your animation on every pixel change. Also, your current ranges have 1px gaps in them because you are doing > instead of >=.

    $(function() {
        var prevRange = -1;
        var range = -1;
    
        $(document).on('scroll', function() {
            var top = $(document).scrollTop();      
            if (top >= 2200 && top < 2401) {
                range = Math.floor(top/10)-220;
            } else {
                range = -1;
            }
    
            if(range != prevRange) {
                prevRange = range;
                var leftPx = (826 - range*5) + "px";
                $('#seta2').stop().animate({left: leftPx}, 300, "easeOutQuad" );
            }
        });
    });
    

    This code finds out which 10px range you are in and then uses that to figure out where to animate to, with the assumption that your ranges are all 10px ranges and the animation ranges are every 5px.

    0 讨论(0)
  • 2021-01-03 11:55

    According to the small part of your code, I think you can found a relation between your top and left value :

    var top = $(document).scrollTop();   
    var left = 826 - Math.floor(top - 2200)/2;
    $('#seta2').stop().animate({left: left+"px"}, 300, "easeOutQuad" );
    
    0 讨论(0)
提交回复
热议问题