簡體   English   中英

交叉點觀察器和動畫數字計數器

[英]Intersection observer and Animated Number Counter

下面代碼的問題是計數器不會同時停止。 有沒有辦法調整計數器的持續時間? 據我所知,通過使用動畫函數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>

您應該使用比率而不是固定數字。

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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM