数字滚动方案

数字滚动方案
分类:前端
标签: Web

使用counterup2

引入资源

<script src="https://unpkg.com/counterup2@2.0.2/dist/index.js"></script>

页面代码

<i class="counter">15</i>
function counterUpInit() {
  if (!window.counterUp) return;
  const counterUp = window.counterUp.default;

  const callback = (entries) => {
    entries.forEach((entry) => {
      const el = entry.target;
      if (entry.isIntersecting && !el.classList.contains("is-visible")) {
        counterUp(el, {
          duration: 1000,
          delay: 16,
        });
        el.classList.add("is-visible");
      }
    });
  };

  const IO = new IntersectionObserver(callback, { threshold: 0.5 });
  document.querySelectorAll(".counter").forEach((el) => {
    IO.observe(el);
  });
}