-2

I have multiple divs on my page where I want to animate their background position onScroll, so here is what I have got for now

/* animate background possition on scroll */
$(window).scroll(function() {
    var y = $(this).scrollTop();
    if(y < $(".page-separator").offset().top && ( $(".page-separator").offset().top ) < ( y + $(window).height() ) ){
        $(this).css('background-position', '0% ' + parseInt(-y / 10) + 'px');
    }
});

But it doesn't work. I think it is because $(this)is not currently visible $(".page-separator") , can you please help me to fix it?


So I have modified my code here but I am stacked again, I can't pass parameter into .each jquery function

$(window).scroll(function() {
    var y = $(window).scrollTop();
    $(".page-separator").each(function(y){
        //$(".page-separator").css('background-position', '0% ' + parseInt(-y / 10) + 'px');
        if( y < $(this).offset().top && ( $(this).offset().top ) < ( y + $(window).height() ) ){
            $(this).css('background-position', '0% ' + parseInt(-y / 10) + 'px');

        }console.log(y);
    });
});

when I see console.log(y) it only shows 0 1 2 nothing more, not the top position

4

2 回答 2

4

要更改background-position可见.page-separator元素的,您可以:

$(window).on('scroll', function() {
    var y = $(window).scrollTop();

    $(".page-separator").filter(function() {
        return $(this).offset().top < (y + $(window).height()) &&
               $(this).offset().top + $(this).height() > y;
    }).css('background-position', '0px ' + parseInt(-y / 10) + 'px');
});

小提琴

于 2013-05-22T16:20:07.967 回答
0

$(this) == $(window)在这种情况下。您应该为所有 div 添加一个类(例如:'animate'),并将其用作选择器(例如$('.animate'):)

于 2013-05-22T16:21:06.490 回答