当用户滚动到页面区域时触发CSS动画

3

我在我的网站上有一个简单的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>

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个回答

5

您需要使用JavaScript才能完成此操作。

在以下示例中,将添加一个scroll事件监听器,并且如果img元素可见,则将animate类添加到#container元素中:

更新的示例

#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');
   }
});

另外,您也可以使用jQuery:

更新示例

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

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接