Trigger a CSS Animation when the user scrolls to page section

后端 未结 1 790
礼貌的吻别
礼貌的吻别 2021-01-01 07:03

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 ani

相关标签:
1条回答
  • 2021-01-01 07:32

    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);
    });
    
    0 讨论(0)
提交回复
热议问题