猿问

如何在 JavaScript 中制作修改后的计数器动画?

我需要创建一个显示两个按钮的网页:“开始”和“停止”。单击“开始”时,我需要每秒显示一个方程。例如:

假设起始数字为100,那么在动画中,网页首先会显示:

100 + 1 = 101

然后每隔一秒,它应该显示:

100 + 2 = 102; 
100 + 3 = 103;
100 + 4 = 104;

等等...每1秒一次。

我已经能够创建计数器动画,但是,我对在此之后如何进展感到困惑。

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

<html>

<head>

  <script>


  var counter = 100;

  var counterSchedule;


  function startCounterAnimation(){


    counterSchedule = setInterval(showCounter, 1000);

  }


  function showCounter(){


    counter = counter + 1;


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

    counterSpan.innerHTML = counter;

  }


  function stopCounterAnimation(){


    clearInterval(counterSchedule);

  }


  </script>

</head>

<body>


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

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


  <br /><br />


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

</body>

</html>

任何帮助将不胜感激!


森林海
浏览 135回答 1
1回答

慕森王

使用下面的代码尝试一下。这就是您要找的吗?&nbsp; var counter = 100;&nbsp; var counterSchedule;&nbsp; let i = 1;&nbsp; function startCounterAnimation(){&nbsp; &nbsp; counterSchedule = setInterval(showCounter, 1000);&nbsp; }&nbsp; function showCounter(){&nbsp; &nbsp; counter = counter + 1;&nbsp; &nbsp; var counterSpan = document.getElementById("counter");&nbsp; &nbsp; counterSpan.innerHTML = `100 + ${i} = ${counter}`;&nbsp; &nbsp; i++;&nbsp; }&nbsp; function stopCounterAnimation(){&nbsp; &nbsp; clearInterval(counterSchedule);&nbsp; }<html><head></head><body>&nbsp; <button onClick="startCounterAnimation()">Start Animation</button>&nbsp; <button onClick="stopCounterAnimation()">Stop Animation</button>&nbsp; <br /><br />&nbsp; <span id="counter"></span></body></html>
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答