当用户滚动到页面部分时触发CSS动画 [英] Trigger a CSS Animation when the user scrolls to page section

查看:970
本文介绍了当用户滚动到页面部分时触发CSS动画的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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).

以下是我的代码:

<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/

推荐答案

您需要使用JavaScript

You need JavaScript to do this.

在下面的示例中,要附加的滚动事件侦听器,如果 img 元素被添加到 #container 元素,$ c> animate visible:

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:

更新示例

#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:


Alternatively, you could also use jQuery as well:

更新示例

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

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

这篇关于当用户滚动到页面部分时触发CSS动画的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆