JavaScript 计数器,达到某些时计数到 3 <div>



我遇到了这个问题。所以我得到了一个计数器,在用户向下滚动页面并到达某个类之后,我想慢慢地从0-3开始计数,在我的例子中是";。domov2";

若我移除API(EventListener(,那个么计数器工作得很好,但它已经在站点加载后立即开始计数了。

我设法做到了这一点,但该函数不是在向下滚动时执行1次,而是在达到div后执行很多次滚动(我对API很不好(。如何将函数限制为执行1次,并在只有条件的情况下保持其运行。

HTML:

<section class="domov2">
Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa. Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem.
</section>
<div id="counter" data-target="3">
-1
</div>

JavaScript

$(window).bind('scroll', function() {
if($(window).scrollTop() >= $('.domov2').offset().top + $('.domov2').outerHeight() - window.innerHeight) {
// create function startCount()
const startCount = function() {
// get number value from data-target and current number
const target = +counter.getAttribute('data-target');
const count = +counter.innerText;
// if count<target 
if (count < target) {
// add to current value +1
var sestevek = count + 1
// replace current value in html with recently updated value "sestevek"
counter.innerText = sestevek;
// slow down condition for 0.3s
setTimeout(startCount, 300);
} else {
//if current value is = target, then keep target
counter.innerText = target;
}};

//execute function
startCount();
}
});

Chris G非常感谢你,我成功了,计数器现在工作得很完美,谢谢你的帮助!

更新的JavaScript:

let countStarted = false;
function somefunction(){
if (countStarted == false){
// create function startCount()
const startCount = function() {
// get number value from data-target and current number
const target = +counter.getAttribute('data-target');
const count = +counter.innerText;
countStarted = true;
// if count<target 
if (count < target) {
// add to current value +1
var sestevek = count + 1
// replace current value in html with recently updated value "sestevek"
counter.innerText = sestevek;
// slow down condition for 0.3s
setTimeout(startCount, 300);
} else {
//if current value is = target, then keep target
counter.innerText = target;
}};
//execute function
startCount();
}}
//execute somefuntion() when div class comes into view area
$(window).bind('scroll', function() {
if($(window).scrollTop() >= $('.domov2').offset().top + $('.domov2').outerHeight() - window.innerHeight) {
somefunction()
}});

最新更新