简体   繁体   中英

CSS3 & jQuery animate on scroll position

having a few issues with my code here. I want brackets to animate whenever they are visible on the screen on the users scroll. My issue is that all of the h2 elements on the page animate at the same time instead when they show in screen. Below is the jQuery used, and here is a link to a jsfiddle:

http://jsfiddle.net/CbxvH/18/

Thanks in advance, Mike.

    $(window).scroll( function(){

        var test1 = $('article h2 span.bracket1');
        var bottom_of_object1 = $(test1).position().top + $(test1).outerHeight();
        var bottom_of_window = $(window).scrollTop() + $(window).height();

        if( bottom_of_window > bottom_of_object1 ){

            $(test1).addClass( "slideLeft" );
            setTimeout(function() {
              $("article h2 .spanContent").animate({'opacity':'1'},1000);
            }, 1000);


    };

        var test2 = $('article h2 span.bracket2');

        var bottom_of_object2 = $(test2).position().top + $(test2).outerHeight();

        if( bottom_of_window > bottom_of_object2 ){

            $(test2).addClass( "slideRight" );

        };

        var test3 = $('article h2 span.bracket3');

        var bottom_of_object3 = $(test3).position().top + $(test3).outerHeight();

        if( bottom_of_window > bottom_of_object3 ){

            $(test3).addClass( "slideLeft" );
            setTimeout(function() {
              $("article h2 .spanContent2").animate({'opacity':'1'},1000);
            }, 1000);

        }

        var test4 = $('article h2 span.bracket4');

        var bottom_of_object4 = $(test4).position().top + $(test4).outerHeight();

        if( bottom_of_window > bottom_of_object4 ){

            $(test4).addClass( "slideRight" );

        }


});

each statement:

$('.featureImages img, article p, article ul li').each( function(i){

        var bottom_of_object = $(this).position().top + $(this).outerHeight();
        var bottom_of_window = $(window).scrollTop() + $(window).height();

        if( bottom_of_window > bottom_of_object ){

            $(this).animate({'opacity':'1'},1000);

        }

    }); 

Have you tried using offset() instead of position() ?

var offset =  $(test1).offset();  
var bottom_of_object1 = offset.top + $(test1).outerHeight();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM