javascript:用于打开和关闭定时颜色更改的按钮

javascript: button to toggle a timed color change on and off

本文关键字:颜色 定时 按钮 用于 javascript      更新时间:2023-09-26

我有一个功能,允许用户输入他们喜欢的计时频率(他们通过文本框输入),将页面上所有div的背景颜色更改为随机生成的颜色。这很有魅力。

但是,我需要包含一个按钮,onClick将打开和关闭定时颜色更改(单击时打开,单击时关闭)。我不知道该怎么做。

当用户在文本框中输入频率时,我在下面包含了用于更改div颜色的代码:

var yourTiming = document.forms["myForm"]["timing"].value;
   function goRandom() {
   var myTiming = setInterval(colourMe, yourTiming);
}
function colourMe() {
    document.getElementById("div1").style.backgroundColor =
            '#'+Math.floor(Math.random()*16777215).toString(16);
    document.getElementById("div2").style.backgroundColor =
            '#'+Math.floor(Math.random()*16777215).toString(16);
    document.getElementById("div3").style.backgroundColor =
            '#'+Math.floor(Math.random()*16777215).toString(16);
    document.getElementById("div4").style.backgroundColor =
            '#'+Math.floor(Math.random()*16777215).toString(16);
}

我不知道如何创建一个函数,当用户单击按钮时,该函数将打开和关闭定时颜色更改。

MDN文档中的示例2似乎展示了您想要实现的目标:https://developer.mozilla.org/en-US/docs/Web/API/WindowTimers/setInterval