gpt4 book ai didi

javascript - 为什么达到目标后就倒计时了?

转载 作者:行者123 更新时间:2023-12-03 05:37:48 24 4
gpt4 key购买 nike

我想要一个只有在实际出现在屏幕上时才会激活的计数器。我已经成功地将它与我发现的其他示例结合在一起。

HTML:

<div>Scroll Down</div>
<span class="count">200</span>

CSS:

div {
height:800px;
background:red;
}
h1 {
display:none;
}

Javascript:

$(window).scroll(function() {
var hT = $('#scroll-to').offset().top,
hH = $('#scroll-to').outerHeight(),
wH = $(window).height(),
wS = $(this).scrollTop();
console.log((hT - wH), wS);
if (wS > (hT + hH - wH)) {
$('.count').each(function() {
$(this).prop('Counter', 0).animate({
Counter: $(this).text()
}, {
duration: 4000,
easing: 'swing',
step: function(now) {
$(this).text(Math.ceil(now));
}
});
});
}
});

演示:

https://jsfiddle.net/76d57vjL/

问题是,它达到 200,然后倒数到 0,但我希望它保持在 200。但我似乎无法弄清楚到底是什么导致了它。

最佳答案

问题是您创建了超过 1 个动画,因此在开始计数后返回到 1,我用一个标志修复了它,但也许您可以制作一些具有高度的东西来检查它。

以下是带有标志的修复:https://jsfiddle.net/uc0av8fh/

var flag = true;
$(window).scroll(function() {
$('#scroll-to');
var hT = $('#scroll-to').offset().top,
hH = $('#scroll-to').outerHeight(),
wH = $(window).height(),
wS = $(this).scrollTop();
console.log((hT-wH) , wS);
if (wS > (hT+hH-wH)){
$('.count').each(function () {
if(!flag) return;
//console.log();
flag = false;
$(this).prop('Counter',0).animate({
Counter: $(this).text()
}, {
duration: 4000,
easing: 'swing',
step: function (now) {
$(this).text(Math.ceil(now));
return 1;
}
});
});
}
});

关于javascript - 为什么达到目标后就倒计时了?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40657141/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com