【问题标题】:Intersection observer and Animated Number Counter交叉口观察者和动画数字计数器
【发布时间】:2021-09-28 04:48:07
【问题描述】:

下面代码的问题是计数器不会同时停止。有什么办法可以调整计数器的持续时间吗?据我所知,通过使用动画函数JQuery 可以调整持续时间,但我想知道如何将其与 Intersection Observer 结合起来,以便在动画数字可见时运行。

const counterElements = document.querySelectorAll(".count");

// Counters
function counter(target, start, stop) {
  target.innerText = 0.1;
  const counterInterval = setInterval(() => {
    start += 0.1;
    const valueConverted = (Math.round(start * 100) / 100).toFixed(1);
    target.innerText = valueConverted;
    if (valueConverted == stop) {
      clearInterval(counterInterval);
    }
  }, 30);
}

function obCallBack(entries) {
  entries.forEach((entry) => {
    const { target } = entry;
    const stopValue = target.innerText;
    const startValue = 0;
    if (!entry.isIntersecting) return;
    counter(target, startValue, stopValue);
    counterObserver.unobserve(target);
  });
}

const counterObserver = new IntersectionObserver(obCallBack, { threshold: 1 });
counterElements.forEach((counterElem) => counterObserver.observe(counterElem));
.emptyspace{
  height:400px;
  }
<div class="emptyspace"></div>
<p class="count">5.2</p>
<p class="count">50.9</p>
</div>

【问题讨论】:

    标签: javascript intersection-observer jquery-countdown


    【解决方案1】:

    您应该使用比率而不是固定数字。

    const speed = 100;
    const inc = Number(stop / speed);
    

    const counterElements = document.querySelectorAll(".count");
    const speed = 100; // the lower the slower
    
    // Counters
    function counter(target, start, stop) {
      target.innerText = 0.1;
      const counterInterval = setInterval(() => {
        const inc = Number(stop / speed);
        start += inc;
        const valueConverted = (Math.round(start * 100) / 100).toFixed(1);
        target.innerText = valueConverted;
        if (valueConverted == stop) {
          clearInterval(counterInterval);
        }
      }, 30);
    }
    
    function obCallBack(entries) {
      entries.forEach((entry) => {
        const { target } = entry;
        const stopValue = target.innerText;
        const startValue = 0;
        if (!entry.isIntersecting) return;
        counter(target, startValue, stopValue);
        counterObserver.unobserve(target);
      });
    }
    
    const counterObserver = new IntersectionObserver(obCallBack, { threshold: 1 });
    counterElements.forEach((counterElem) => counterObserver.observe(counterElem));
    .emptyspace{
      height:400px;
      }
    <div class="emptyspace"></div>
    <p class="count">5.2</p>
    <p class="count">50.9</p>
    </div>

    【讨论】:

      猜你喜欢
      • 2018-11-22
      • 1970-01-01
      • 2022-01-17
      • 2023-04-06
      • 1970-01-01
      • 1970-01-01
      • 2022-01-18
      • 2021-07-20
      相关资源
      最近更新 更多