如何在 JavaScript 中制作计数动画?

好的,所以我必须显示一个文本字段,以便用户可以输入一个整数。然后显示“开始动画”和“停止动画”两个按钮。


当单击“开始动画”按钮时,网页以下列方式显示动画时间表。


例如,如果用户输入数字 6,则动画显示


6 x 1 = 6,一秒后用 6 x 2 = 12 替换,一秒后用 6 x 3 = 18 替换,以此类推。如果是 6 x 9 = 54,则一秒后它变成 6 x 1 = 6,然后 6 x 2 = 12,依此类推。


当点击“停止动画”按钮时,网页停止动画。无论当前显示的方程式如何,都将保留在页面上。


这是我到目前为止的代码。


var counter = 0;

var counterSchedule;


function startCounterAnimation() {

  // start the counter animation

  counterSchedule = setInterval(showCounter, 1000);

}


function showCounter() {

  // increase the counter by 1

  counter = counter + 1;

  // show the counter

  var counterSpan = document.getElementById("counter");

  counterSpan.innerHTML = counter;

}


function stopCounterAnimation() {

  clearInterval(counterSchedule);

}

<input id="number" type="text">

<button onclick="startCounterAnimation()">Start Animation</button>

<button onclick="stopCounterAnimation()">Stop Animation</button>

<br/><br/>

<span id="counter"></span>


白板的微信
浏览 145回答 2
2回答

眼眸繁星

我不明白你到底想要什么帮助,但我根据我的理解修复了它var counter = 0;var counterSchedule;var input = document.getElementById("number");var counterSpan = document.getElementById("counter");function startCounterAnimation() {&nbsp; counterSchedule = setInterval(showCounter, 1000);}function showCounter() {&nbsp; if (~~input.value) {&nbsp; &nbsp; &nbsp; if (counter >= 10)&nbsp; &nbsp; &nbsp; &nbsp; counter = 0;&nbsp; &nbsp; &nbsp; counter++;&nbsp; &nbsp; &nbsp; counterSpan.innerHTML = input.value + " X " + counter + " = " + eval(input.value + " * " + counter);&nbsp; &nbsp; }&nbsp; }&nbsp; function stopCounterAnimation() {&nbsp; &nbsp; clearInterval(counterSchedule);&nbsp; &nbsp; input.value = "";&nbsp; &nbsp; counter = 0;&nbsp; }<input onClick="stopCounterAnimation()" id="number" type="text"><button onclick="startCounterAnimation()">Start Animation</button><button onclick="stopCounterAnimation()">Stop Animation</button><br/><br/><span id="counter"></span>

四季花海

我不确定我是否正确理解了您的问题(我真的没有看到问题)。您的代码看起来不错,但您希望它在达到 10 后重新开始?尝试使用模运算符 % 所以替换counterSpan.innerHTML = counter;和counterSpan.innerHTML = counter % 10;告诉我我是否误解了这个问题。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

JavaScript