首页 > 解决方案 > 添加一个类到

问题描述

我的网站上的css,但我希望动画仅在元素出现在页面上时开始。

我有这样的事情:

HTML

<footer id="footer" class="animate__animated">
    <div class="footer-all">
        <img src="img/logo-hero@2x.png" alt="" class="logo-footer">
        <p class="copyright">CASA DI AMICI C 2020 All rights reserved</p>
    </div>
</footer>

CSS 规范:安装 Animate.css 后,将类 animate__animated 与任何动画名称一起添加到元素中。动画名称:animate__fadeIn

JS

let footer = document.getElementById("footer");

window.addEventListener("scroll", function() {

    footer.classList.add('animate__fadeIn'); 
});

但是“滚动”不起作用,我尝试加载但仍然不起作用。请在这件事上给予我帮助

标签: javascriptcssanimate.css

解决方案


正如 TKoL 所提到的,您可以查看 Intersection Observer API。但是如果你想要一个更简单的解决方案,我在 Codepen 上创建了这个例子

function isInView(el) {
   let box = el.getBoundingClientRect();
   return box.top < window.innerHeight && box.bottom >= 0;
}

window.addEventListener("scroll", function() {
  var footer = document.getElementById("footer");
  var visible = isInView(footer);
    if(visible) {
      footer.classList.add("animate__fadeIn");
    } else {
      footer.classList.remove("animate__fadeIn");
    }
});

isInView功能在此答案中找到


推荐阅读