Trigger a CSS Animation when the user scrolls to page section

谁说胖子不能爱 提交于 2019-11-29 23:26:00

问题


I have a simple CSS animation on my site, where I want to show 5 divs showing one at a time in a row.

Everything works fine, but I want to make a trigger to that animation, when the user scrolls to that particular section on my site(now the animation starts when the page loads).

Here is my code:

<div id="space"></div>
<div id="container">
  <img src="https://cdn1.iconfinder.com/data/icons/user-pictures/100/male3-64.png" />
  <img src="https://cdn1.iconfinder.com/data/icons/user-pictures/100/male3-64.png" /> 
  <img src="https://cdn1.iconfinder.com/data/icons/user-pictures/100/male3-64.png" />
  <img src="https://cdn1.iconfinder.com/data/icons/user-pictures/100/male3-64.png" />
  <img src="https://cdn1.iconfinder.com/data/icons/user-pictures/100/male3-64.png" />
</div>

CSS:

#space {
    height: 700px;
    background-color: blue;
}
#container img {
    opacity: 0;
}
@keyframes fdsseq { 
    100% { opacity: 1; }
}
#container img {
    animation: fdsseq .5s forwards;
}
#container img:nth-child(1) {
    animation-delay: .5s;
}
#container img:nth-child(2) {
    animation-delay: 1s;
}
#container img:nth-child(3) {
    animation-delay: 1.5s;
}
#container img:nth-child(4) {
    animation-delay: 2s;
}
#container img:nth-child(5) {
    animation-delay: 2.5s;
}

https://jsfiddle.net/Lwb088x5/


回答1:


You need JavaScript to do this.

In the example(s) below, a scroll event listener to attached, and the animate class is added to the #container element if the img elements are visible:

Updated Example

#container.animate img {
  animation: animation .5s forwards;
}
document.addEventListener('scroll', function (e) {
  var top  = window.pageYOffset + window.innerHeight,
      isVisible = top > document.querySelector('#container > img').offsetTop;

   if (isVisible) {
     document.getElementById('container').classList.add('animate');
   }
});

Alternatively, you could also use jQuery as well:

Updated Example

$(window).on('scroll', function (e) {
   var top = $(window).scrollTop() + $(window).height(),
       isVisible = top > $('#container img').offset().top;

   $('#container').toggleClass('animate', isVisible);
});


来源:https://stackoverflow.com/questions/34474565/trigger-a-css-animation-when-the-user-scrolls-to-page-section

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