我的页面包含一个计数器,我想添加一个方法,使计数器在达到某个高度时启动。我已经计算出我希望计数器从 324px 的高度开始,但由于我对 JavaScript 的经验很少,我不确定我在寻找什么。有人能帮我吗?
这是我当前的代码:
const counters = document.querySelectorAll('.counter');
const speed = 2000;
counters.forEach(counter => {
const updateCount = () => {
const target = counter.getAttribute('data-target');
const count = counter.innerText;
const inc = target / speed;
if (count < target) {
counter.innerText = Math.ceil(count inc);
requestAnimationFrame(updateCount, 1);
} else {
count.innerText = target;
}
}
updateCount();
});
<div class="container-b">
<div class="container">
<div class="row">
<div class="counters">
<div class="card-image" id="purple-b">
<i class="fas fa-users"></i>
<div class="counter" data-target="231">0</div>
<p class="card-b-text">Happy Users</p>
</div>
<div class="card-image" id="green-b">
<i class="fas fa-code"></i>
<div class="counter" data-target="385">0</div>
<p class="card-b-text">Issues Solved</p>
</div>
<div class="card-image" id="red-b">
<i class="fas fa-cog"></i>
<div class="counter" data-target="159">0</div>
<p class="card-b-text">Good Reviews</p>
</div>
<div class="card-image" id="orange-b">
<i class="fas fa-comments"></i>
<div class="counter" data-target="127">0</div>
<p class="card-b-text">Case Studies</p>
</div>
<div class="card-image" id="blue-b">
<i class="fas fa-rocket"></i>
<div class="counter" data-target="211">0</div>
<p class="card-b-text">Orders Received</p>
<p></p>
</div>
</div>
</div>
</div>
</div>
uj5u.com热心网友回复:
我不知道这是否是你要找的东西。如果有错你可以多描述一下,因为我不太明白。
假设我有一个 3000px CSS 的页面:
.counter{
height: 3000px;
}
我希望每当我滚动通过 324px 时,它都会为你做一些事情
const counters = document.querySelectorAll('.counter');
window.onscroll=function(){
if(scrollY >= 324){
console.log("Do your start count things or something in here")
}
}
uj5u.com热心网友回复:
我会这样做:
对两个元素使用相同requestAnimationFrame()
的,并在没有更新时停止它
const
speed = 2000
, counters = [...document.querySelectorAll('.counter')]
.map(el=>(
{ el
, target : el.dataset.target
, inc : (el.dataset.target / speed)
, count : parseInt(el.textContent)
}))
;
requestAnimationFrame(updateCount)
function updateCount()
{
let elmsRun = counters.length
counters.forEach(({ el, target, inc, count}, i) =>
{
el.textContent = counters[i].count
= (count < target) ? Math.ceil(count inc) : target
if (counters[i].count === target) --elmsRun
})
if (elmsRun) requestAnimationFrame(updateCount)
}
0 评论