我正在学习,所以请客气:-)
我找到了完美的倒计时时钟。
我想要实现的是在1
一词之后出现Lift Off!
,但是由于某种原因,倒数时钟一直显示1
var startNum;
var currentNum;
function addClassDelayed(jqObj, c, to) {
setTimeout(function() { jqObj.addClass(c); }, to);
}
function anim() {
addClassDelayed($("#countdown"), "puffer", 600);
if (currentNum == 0) $('#countdown').html("Lift Off!"); else currentNum--;
$('#countdown').html(currentNum+1);
$('#countdown').removeClass("puffer");
}
$(function() {
startNum = 5;
currentNum = startNum;
$("#countdown").html(currentNum); // init first time based on n
self.setInterval(function(){anim()},1325);
});
答案 0 :(得分:2)
$('#countdown').html(currentNum+1);
会覆盖您之前设置的所有内容。
function anim() {
addClassDelayed($("#countdown"), "puffer", 600);
if (currentNum == 0) {
$('#countdown').html("Lift Off!");
clearInterval(token)
} else {
currentNum--;
$('#countdown').html(currentNum+1); // Only show if not "Lift Off!"
}
$('#countdown').removeClass("puffer");
}
var token;
$(function() {
startNum = 5;
currentNum = startNum;
$("#countdown").html(currentNum); // init first time based on n
token = self.setInterval(function(){anim()},1325);
});
根据泰勒的建议添加了clearInverval
答案 1 :(得分:2)
让我们看看您的动画功能:
function anim() {
addClassDelayed($("#countdown"), "puffer", 600);
if (currentNum == 0) $('#countdown').html("Lift Off!"); else currentNum--;
$('#countdown').html(currentNum+1);
$('#countdown').removeClass("puffer");
}
如果在if语句后缺少括号,则暗示它们仅适用于以下语句(单数)。基于此,让我们在隐含代码的部分添加括号:
function anim() {
addClassDelayed($("#countdown"), "puffer", 600);
if (currentNum == 0) {
$('#countdown').html("Lift Off!");
} else {
currentNum--;
}
$('#countdown').html(currentNum+1);
$('#countdown').removeClass("puffer");
}
基于此,当currentNum为0时,#countdown
的内容变为“ Lift Off!”。然后立即更改为currentNum + 1
。这就是为什么它永远不会通过显示“ Lift Off!”结束。
此代码将打印“提起!”或当前数字(被引用后递减):
var startNum;
var currentNum;
var countdownInterval;
function addClassDelayed(jqObj, c, to) {
setTimeout(function() { jqObj.addClass(c); }, to);
}
function anim() {
addClassDelayed($("#countdown"), "puffer", 600);
if (currentNum === 0) {
$('#countdown').html('Lift Off!');
clearInterval(countdownInterval);
} else {
$('#countdown').html(currentNum--);
}
$('#countdown').removeClass("puffer");
}
$(function() {
startNum = 5;
currentNum = startNum;
$("#countdown").html(currentNum); // init first time based on n
countdownInterval = self.setInterval(function(){anim()},1325);
});
答案 2 :(得分:1)
您的代码中有错误。您在Lift off!
if
语句之后覆盖了else
。
function anim() {
addClassDelayed($("#countdown"), "puffer", 600);
// Add a return statement here.
if (currentNum == 0) {
$('#countdown').html("Lift Off!");
return;
}
else {
currentNum--;
}
$('#countdown').html(currentNum+1);
$('#countdown').removeClass("puffer");
}