【问题标题】:Trigger a CSS Animation when the user scrolls to page section当用户滚动到页面部分时触发 CSS 动画
【发布时间】:2015-12-26 19:36:55
【问题描述】:

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

【问题讨论】:

    标签: html css css-animations


    【解决方案1】:

    您需要 JavaScript 来执行此操作。

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

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

    或者,您也可以使用 jQuery:

    Updated Example

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

    【讨论】:

      猜你喜欢
      • 2017-01-06
      • 1970-01-01
      • 2014-06-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-10
      • 1970-01-01
      相关资源
      最近更新 更多