我想补充一些网站现在有的效果,即咖啡喝了:然后喝了多少咖啡,逐渐从0增加到N-1。这是我的尝试,如果我在第一个if语句中在控制台中打印i,则打印出每个数字。但是,当它在HTML中时它会立即从0到950,而中间没有数字。
总结一下:我想在页面上增加数字,每个新数字都会替换之前的数字。
for (i = 0; i < 950; i++) {
if ($("#counter").length) {
setTimeout(function() {
// body...
$("#counter").append('<p id = "counter">' + i + '</p>');
}, 2000);
console.log(i);
} else {
$(".coffee-drank").append('<p id = "counter">' + i + '</p>');
}
}
答案 0 :(得分:0)
如果我的想法正确,可以像这样做:
var start = -1, end = 950;
var countUp = function func() {
if(start >= end) return;
var elem = document.getElementById("counter");
elem.innerText = ++start;
setTimeout(func, 25);
}
countUp();
&#13;
count up to 950:
<span id="counter">0</span>
&#13;
<强>更新强> 在你的情况下,它可能看起来像这样(根本不需要一个循环):
var start = -1, end = 950;
var countUp = function func() {
if(start >= end) {
// the end is reached; start is equal to 950 now; do something useful and quit
$(".coffee-drank").append('<p id = "counter">' + start +'</p>');
return;
}
$("#counter").text(++start);
setTimeout(func, 25);
}
countUp();
答案 1 :(得分:0)
用以下代码取代你的for循环:
var speed = 16; // Lower is faster
increase(0, 950);
function increase(i, max){
if(i <= max){
if ($("#counter").length) {
$("#counter").html(i);
} else {
$(".coffee-drank").append('<p id = "counter">' + i + '</p>');
}
setTimeout(function(){
increase(++i, max);
}, speed);
}
}