【问题标题】:Adding a class to <footer> element when it is visible (in viewport)当 <footer> 元素可见时添加一个类(在视口中)
【发布时间】:2020-11-19 14:07:08
【问题描述】:

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

但是“滚动”不起作用,我尝试加载但仍然不起作用。 请帮我解决这个问题

【问题讨论】:

  • 我敢肯定,这对你来说会有很多东西需要咀嚼——它是给我的——但是有一个叫做 Intersection Observer api 的东西,它允许你在元素出现时注册回调映入眼帘
  • 据我记忆,这不是很方便,但它确实有效

标签: javascript css animate.css


【解决方案1】:

正如 TKoL 所述,您可以查看 Intersection Observer API。 但是如果你想要一个更简单的解决方案,我创建了这个example on 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");
    }
});

在这个answer中发现了isInView函数

【讨论】:

    【解决方案2】:

    我找到了类似的东西,使用 jQuery http://www.web2feel.com/freeby/scroll-effects/index5.html

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-15
      • 2010-09-12
      相关资源
      最近更新 更多