我如何使用clearInterval()或其他一些方法,使我的背景渐变脚本在javascript中使用setInterv

How can I use clearInterval() or some other method to make my fade background script in javascript that uses setInterval() stop?

本文关键字:渐变 背景 我的 脚本 setInterv javascript 方法 clearInterval 何使用 其他      更新时间:2023-09-26

我有一个嵌套的闭包函数,它根据数组中的赋值循环和褪色背景色。在按钮上与onclick"stopFadeColors()"方法我开始,我怎么能通过单击第二个按钮,实际上停止脚本运行?

<style>
.black {
    -moz-transition: all .2s ease-in;
    -o-transition: all .2s ease-in;
    -webkit-transition: all .2s ease-in;
    transition: all .2s ease-in;
    background: #000;
}
.white {
    -moz-transition: all .2s ease-in;
    -o-transition: all .2s ease-in;
    -webkit-transition: all .2s ease-in;
    transition: all .2s ease-in;
    background: #fff;
}
</style>
<script>
//make the element start blinking at a rate of once per second.
function fadeColors(target) {
    var elem = document.body; //assign the object to a shorter named object
    var toggleColor = ["black", "white"]; // setup color list, it can be more than two
    var counter = 0; //outer counter
    var nextColor; //outerClass
    function changeBackgroundColor() {
        console.log(counter); // output count 
        counter = (counter + 1) % toggleColor.length; //modulus of counter divided by counter length
        nextColor = toggleColor[counter]; //update the class 
        elem.className = nextColor; //assign the class
    }
    setInterval(changeBackgroundColor, 1000); //call our function 
}
</script>
<button onclick="fadeColors()">Fade Background</button>
<!-- how can i make this next button call a new or existing method and pause the script with clearInterval() or some other way? --//>
<button onclick="stopFadeColors()">Stop Fade Background</button>

您需要将您的setInterval()函数分配给一个变量:

function fadeColors(target) {
    var elem = document.body; //assign the object to a shorter named object
    var toggleColor = ["black", "white"]; // setup color list, it can be more than two
    var counter = 0; //outer counter
    var nextColor; //outerClass
    function changeBackgroundColor() {
        console.log(counter); // output count 
        counter = (counter + 1) % toggleColor.length; //modulus of counter divided by counter length
        nextColor = toggleColor[counter]; //update the class 
        elem.className = nextColor; //assign the class
    }
    document['intervalTemp'] = setInterval(changeBackgroundColor, 1000); //call our function 
}
HTML:

<button onclick="fadeColors();">Fade Background</button>

其他按钮点击停止:

<button onclick="clearInterval(document.intervalTemp);">Stop Fade Background</button>