run css animation when visible on scroll

女生的网名这么多〃 提交于 2020-12-15 06:28:20

问题


I'm creating my test webpage and I ran into a problem, there are quite a few "answers" on my issue but none was I able to implement in my code. I know I have to use javascript but I was not able to get it working.

So, I need to run css animation of movement on chosen picture, when that picture is visible on screen when I scroll down to it. Basically like on this page: https://www.photoblog.com/

So I have this code in the html as for the picture:

<img class="movepic" src="pictures/test.jpg">

And then there is this simple code for the CSS movement:

.movepic {
position: relative;
animation-name: move;
animation-duration: 3s;
visibility: visible;
animation-fill-mode: forwards;
z-index:10;
}
@keyframes move {
0% { right:0px; top:150px;}
100% {right:700px; top:150px;}
}

Is there a way to make it work so I do not need to completely redo this? Or if so, could some please give me a advice how to do it maybe with code ilustration.

Thanks a lot


回答1:


Remove the animation-name from your style rule:

.movepic {
    position: relative;
    animation-duration: 3s;
    animation-fill-mode: forwards
    visibility: visible;
    z-index:10;
} 

and add this class to stylesheet:

.animation-class {
    animation-name: move
}

Now add the jQuery:

var has_fired;
$("html").on("scroll", function () {
    if (!has_fired && $(this).scrollTop() >= $("#imgContainer").offset().top) {
        $("#imgContainer").addClass("animation-class");
        has_fired = true; // use this if only want fired once
    }
});

The animation will now run. BTW I would add an ID (imgContainer) to your container of interest and use this as selector for matching because unless .movepic is a unique class, this function will fire for any container with the .movepic class (if .movepic is the selector).




回答2:


I use this code for this effect:

HTML:

<img class="movepic" src="pictures/test.jpg">

CSS:

.movepic {
  opacity: 0;
  margin: 25px 0 0;
  color: white;
  padding: 10px;
 }

.FadeIn {
    -webkit-animation: slideIn 0.8s ease 0.3s forwards;
    animation: slideIn 0.8s ease 0.3s forwards;
}

@keyframes slideIn {
    0% {
        -webkit-transform: translateY(40px);
        opacity: 0;
    }
    100% {
        -webkit-transform: translateY(0px);
        opacity: 1;
    }
}

JQuery:

var $fade =  $(".movepic"); //Calling the class in HTML

$(window).scroll(function () { //Using the scroll global variable
    $fade.each(function () {

        fadeMiddle = $(this).offset().top + (0.4 *$(this).height());
        windowBottom = $(window).scrollTop() + $(window).height();

        if (fadeMiddle < windowBottom) {
          $(this).addClass("FadeIn");
        }
    });
});

/* On Load: Trigger Scroll Once*/
$(window).scroll();


来源:https://stackoverflow.com/questions/50626766/run-css-animation-when-visible-on-scroll

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!