javascript - 在 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>
解决方案
一点解释。我已经使用您的代码创建了一个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"
推荐阅读
- php - Bootstrap 4:将行月份名称动态添加到表中
- excel - If 函数具有多个条件。IFS 确实
- javascript - 检查字符串是否包含 'abc' 或 'cde' 并开玩笑
- c++ - 模板类中模板类的函数返回类型
- javascript - 尝试将数组传递给 React 中的子组件时得到未定义的映射
- python-3.x - 无法使用 python-64Bit 连接到 Access 数据库
- drupal - Drupal 8 树枝日期字段输出今天的日期而不是字段的日期
- c# - Ef 核心外键违规但键存在且在添加实体时填充
- c# - 如何在不输入Visual Studio的情况下剪切/粘贴方法签名?
- sql - 计算连接返回的行数