我正在尝试使用 onclick 函数更改这两个框的速度(setinterval)。 到目前为止,我让两个框改变颜色,并将Interval设置为1000(ms),现在我想单击其中一个框,我希望它们改变颜色的速度。
setInterval(
function(){
if (quadraDo == true) {
document.getElementById("demo0").style.background = "red"
document.getElementById("demo1").style.background = "blue";
quadraDo = false;
}
else if (quadraDo == false) {
document.getElementById("demo0").style.background = "blue";
document.getElementById("demo1").style.background = "red";
quadraDo = true;
}
}, 1000);
<div id="demo0" style="position: absolute;background-color: chartreuse ; width: 100px;height: 100px;left: 100px;top: 100px;" onclick="myFunction(this)"></div>
<div id="demo1" style="position: absolute;background-color: chartreuse ; width: 100px;height: 100px;left: 300px;top: 100px;" onclick="myFunction(this)"></div>
最佳答案
一些解释。我使用您的代码创建了一个函数 changeColor
,该函数的初始间隔速度为 1000ms
然后,单击任何一个方 block 后,初始计时器将被清除,并以不同的间隔速度开始新的计时器。在这种情况下:
- 点击第一个方 block 会减慢初始节奏 (x0.5) 或 500 毫秒
- 点击第二个可加快初始节奏 (x2) 或 2000 毫秒
这样 myFunction
就可以被重用来设置初始速度并在单击时更改速度。最重要的部分是在开始新的间隔之前清除当前的间隔。
let quadraDo = false;
function changeColor() {
if (quadraDo == true) {
document.getElementById("demo0").style.background = "red";
document.getElementById("demo1").style.background = "blue";
quadraDo = false;
} else if (quadraDo == false) {
document.getElementById("demo0").style.background = "blue";
document.getElementById("demo1").style.background = "red";
quadraDo = true;
}
}
function myFunction(speed) {
clearInterval(timer);
timer = setInterval(changeColor, speed);
}
let timer = setInterval(changeColor, 1000);
<div id="demo0" style="position: absolute;background-color: chartreuse ; width: 100px;height: 100px;left: 100px;top: 100px;" onclick="myFunction(500)"></div>
<div id="demo1" style="position: absolute;background-color: chartreuse ; width: 100px;height: 100px;left: 300px;top: 100px;" onclick="myFunction(2000)"></div>
顺便说一句,您在复制粘贴代码时出现拼写错误:
document.getElementById.setInterval("demo0",100).style.background = "red"
应该是:
document.getElementById("demo0").style.background = "red"
关于javascript - 更改 onclick 处的 Setinterval,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58996689/