首页 > 解决方案 > 在 onclick 更改 Setinterval

问题描述

我试图用 onclick 功能改变这两个盒子的速度(setinterval)。到目前为止,我让两个框改变颜色,我 setInterval 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>

标签: javascripthtml

解决方案


一点解释。我已经使用您的代码创建了一个changeColor以 1000 毫秒的初始间隔速度工作的函数

然后在单击任何方块时,初始计时器将被清除,并以不同的间隔速度启动新计时器。在这种情况下:

  • 单击第一个方块会减慢初始速度 (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"

推荐阅读