简体   繁体   中英

Trigger animation on scroll down

Here i creat animation that turns from color to grayscale but i want it will start only when user will scroll down (as it's in my site with a lot of images and need to scroll down to get there)

here is the fiddle example: http://jsfiddle.net/4tHWg/7/

 .box {
       float: left;
       position: relative;
       width: 14.285714286%;



    }

    .boxInner img {
       width: 100%;
       display: block;

    }

    .boxInner img:hover {
      -webkit-filter: grayscale(0%);
    }

@-webkit-keyframes toGrayScale {
    to {
        -webkit-filter: grayscale(100%);
    }
}

.box:nth-child(1) img {
    -webkit-animation: toGrayScale 1s 0.5s forwards;
}

.box:nth-child(2) img {
    -webkit-animation: toGrayScale 2s 1s forwards;
}

.box:nth-child(3) img {
    -webkit-animation: toGrayScale 3s 1.5s forwards;
}

This should do the trick.

$( window ).scroll(function() {
    $(".box").each(function (index){
        if (index == 1)
        {
            $(":nth-child("+index+")", $(this)).css('-webkit-animation','toGrayScale 1s 0.5s forwards');
        }
        if (index == 2)
        {
            $(":nth-child("+index+")", $(this)).css('-webkit-animation','toGrayScale 2s 1s forwards');
        }
        if (index == 2)
        {
            $(":nth-child("+index+")", $(this)).css('-webkit-animation','toGrayScale 3s 1.5s forwards');
        }
    });

If I understand correctly what you are looking to do, then you can handle scrolling with .scroll() function. Then trigger the animation if the windows .scrollTop() reaches each .box 's offset().top .

$(window).scroll(function(){
    var st = $(this).scrollTop();

    $('.box').each(function(index, element){
        if(st >= $(this).offset().top){
            $(this).find('img').css({'-webkit-animation':'toGrayScale 1s 1s forwards'});
        }
    });
});

Here is the updated fiddle .

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