Javascript: Countdown by animation.width()



我目前正在尝试为我的用户制作动画完成时的视觉倒计时。我目前的尝试看起来有点像这样:

function setClassAndFire(){
timer = setInterval(function () {
t--;
$(this).attr('class', 'timerAnimation');
countdownTimer();
if (t === 0) {
clearInterval(timer);
timer = undefined;
funcForCall();
}
}, 1000);  
}
function countdownTimer(){
var timerCurrentWidth = $('.timerAnimation').width(),
timerMaxWidth = $("#awardQueueText").width(),
pxPerSecond = timerMaxWidth / 60,
currentCountdown = timerCurrentWidth / pxPerSecond;
currentCountdown = Math.round(currentCountdown);
document.getElementById("timer").innerHTML = "<span style='white-space : nowrap;'>Animation ends in:</br></span>"+
"<span style='white-space : nowrap;'>" + currentCountdown + " sec.</span>";
}

重要的是要知道,动画仅显示我们可能能够发送 API 调用的时间。因此,如果我们有东西在排队,动画将被重新参与。

所以正如你所看到的,我目前的尝试是有效的,但有些笨拙:

倒计时有时无法减去一秒并"修复" 在下一次尝试中减去 2 秒。

这可能是由当前倒计时Math.round((引起的,但有解决方法吗?我的意思是我有动画对象的最大可能宽度,并且可以将其与当前宽度分开。

有没有办法让它发挥作用?我们需要将计时器与动画相关联以实现所需的行为。因此,当动画计数达到 25 时,我希望显示的数字也是 25!

你遇到了这个问题,因为你从宽度中得到了数字,宽度不能有小数(或者更好的是,它们可以是,但它们有时会被截断(。 所以我的建议是使用不同的变量来表示您将显示的数字和 DOM 元素的宽度。 在我看来,变量t就是我在说的,所以试着使用它。

function setClassAndFire(){
timer = setInterval(function () {
t--; //What is t? 
$(this).attr('class', 'timerAnimation');
countdownTimer(t);
if (t === 0) {
clearInterval(timer);
timer = undefined;
funcForCall();
}
}, 1000);  
}
function countdownTimer(t){
document.getElementById("timer").innerHTML = "<span style='white-space : nowrap;'>Animation ends in:</br></span>"+
"<span style='white-space : nowrap;'>" + t+ " sec.</span>";
}

最新更新