通过onclick循环更改背景颜色 [英] Change background color with a loop onclick
本文介绍了通过onclick循环更改背景颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
这是我的js小提琴: http://jsfiddle.net/pYM38/16/
here is my js fiddle : http://jsfiddle.net/pYM38/16/
var box = document.getElementById('box');
var colors = ['purple', 'yellow', 'orange', 'brown', 'black'];
box.onclick = function () {
for (i = 0; i < colors.length; i++) {
box.style.backgroundColor = colors[i];
}
};
我正在学习JavaScript.我试图让它遍历数组中的每种颜色,但是当我单击框(在jsfiddle上的演示)时,它将转到数组中的最后一个元素.
I'm in the process of learning JavaScript. I was trying to get this to loop through each color in the array, but when i click the box (demonstration on jsfiddle) it goes to the last element in the array.
推荐答案
以下是两种方法,具体取决于您要执行的操作:
Here are two methods, depending on what you're up to:
点击后进入下一步
var box = document.getElementById('box'),
colors = ['purple', 'yellow', 'orange', 'brown', 'black'];
box.onclick = function () {
color = colors.shift();
colors.push(color);
box.style.backgroundColor = color;
};
点击全览
var box = document.getElementById('box'),
colors = ['purple', 'yellow', 'orange', 'brown', 'black'];
box.onclick = function () {
(function loop(){
var color = colors.shift();
box.style.backgroundColor = color;
if (colors.length) {
setTimeout(loop, 1000);
}
})();
};
在下次点击时重新启动
var box = document.getElementById('box'),
colors = ['purple', 'yellow', 'orange', 'brown', 'black'];
box.onclick = function () {
var set = colors.slice(0);
(function loop(){
var color = set.shift();
box.style.backgroundColor = color;
if (set.length) {
setTimeout(loop, 1000);
}
})();
};
这篇关于通过onclick循环更改背景颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文