我如何使用clearInterval()或其他一些方法,使我的背景渐变脚本在javascript中使用setInterv
How can I use clearInterval() or some other method to make my fade background script in javascript that uses setInterval() stop?
我有一个嵌套的闭包函数,它根据数组中的赋值循环和褪色背景色。在按钮上与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>
相关文章:
- 画布使用带有角度的线性渐变背景集
- 我怎么能有一个自动渐变背景使用JavaScript,它适用于最新版本的Internet Explorer
- 如何在每次页面重新加载时更改渐变背景,同时保持光标位置元素处于活动状态
- Highchart条形图中的渐变背景条形图
- 通过程序添加CSS渐变作为背景图像
- 动画渐变(javascript)背景不会延伸到窗口的整个高度
- 在具有动态高度的背景图像上创建渐变覆盖
- 使用javascript更改背景图像时保持渐变不变
- 使用 ng 样式进行背景渐变时出现 AngularJS 语法错误
- 我将如何在JavaScript中设置CSS渐变背景
- 背景图像本身的 CSS 渐变
- 弹跳球在JavaScript上与背景和渐变
- 使用Javascript有没有办法抓取由线性或径向渐变渲染的背景图像
- 生成渐变 css / svg 背景
- 鼠标移动时更改渐变背景颜色
- 改变渐变背景的颜色(Chrome)
- CSS z索引渐变背景
- 我如何设置不同的渐变背景,每次用户刷新
- 使用CSS3渐变背景和前后伪元素
- 渐变背景横幅图像,可自动调整窗口当前宽度的大小