我需要创建一个显示两个按钮的网页:“开始”和“停止”。单击“开始”时,我需要每秒显示一个方程。例如:假设起始数字为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>任何帮助将不胜感激!
1 回答
慕森王
TA贡献1777条经验 获得超3个赞
使用下面的代码尝试一下。这就是您要找的吗?
var counter = 100;
var counterSchedule;
let i = 1;
function startCounterAnimation(){
counterSchedule = setInterval(showCounter, 1000);
}
function showCounter(){
counter = counter + 1;
var counterSpan = document.getElementById("counter");
counterSpan.innerHTML = `100 + ${i} = ${counter}`;
i++;
}
function stopCounterAnimation(){
clearInterval(counterSchedule);
}
<html>
<head>
</head>
<body>
<button onClick="startCounterAnimation()">Start Animation</button>
<button onClick="stopCounterAnimation()">Stop Animation</button>
<br /><br />
<span id="counter"></span>
</body>
</html>
添加回答
举报
0/150
提交
取消