当用户滚动到页面部分时触发 CSS 动画

num*_*333 3 html css css-animations

我的网站上有一个简单的 CSS 动画,我想在其中显示 5 个 div,一次显示一个。

一切正常,但我想触发该动画,当用户滚动到我网站上的特定部分时(现在动画在页面加载时开始)。

这是我的代码:

<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>
Run Code Online (Sandbox Code Playgroud)

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;
}
Run Code Online (Sandbox Code Playgroud)

https://jsfiddle.net/Lwb088x5/

Jos*_*ier 5

您需要 JavaScript 来执行此操作。

在下面的示例中,scroll附加了一个事件侦听器,如果元素可见,则将animate类添加到元素中:#containerimg

更新示例

#container.animate img {
  animation: animation .5s forwards;
}
Run Code Online (Sandbox Code Playgroud)
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');
   }
});
Run Code Online (Sandbox Code Playgroud)

或者,您也可以使用 jQuery:

更新示例

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

   $('#container').toggleClass('animate', isVisible);
});
Run Code Online (Sandbox Code Playgroud)