我将随机背景颜色(从3个调色板)应用到页面的不同部分。但是,我想确保相同的颜色不会连续出现两次。
我认为一个小do
while
循环可以正常工作,但它看起来并不完全。
var colours = new Array('#FF5A5A', '#FFBE0D', '#00DDB8');
var divs = $('.row');
var last;
var next;
// for each section
divs.each(function(i){
// get a random colour
do {
next = Math.floor(Math.random()*3);
// if it's the same as the last one, try again!
} while( next === last ) {
next = Math.floor(Math.random()*3);
}
// when it's different to the last one, set it
$(this).css('background-color', colours[next] );
// tell it this is the last one now
next = last;
});
有什么想法吗?
答案 0 :(得分:2)
这是一种语法错误 - 你无法决定你是想要一个do-while-loop还是一个普通的while循环?你把它放在那里将被解释为一个简单的block:
do {
next = Math.floor(Math.random()*3);
} while( next === last ) // end of the do-while-loop!
// Block here - the braces could be omitted as well:
{
next = Math.floor(Math.random()*3);
}
$(this).css('background-color', colours[next] );
…
这将正确计算与最后一个不同的数字,但随后它将使用新的(不受限制的)随机数覆盖它。此外,作业next = last;
与你想要的完全相反。
所以将脚本更改为
do {
next = Math.floor(Math.random()*3);
} while( next === last ) // if it's the same as the last one, try again!
// tell it this is the last one now
last = next;
// now that we've made sure it's different from the last one, set it
$(this).css('background-color', colours[next] );
答案 1 :(得分:1)
修订 - (因为我感受到了挑战!)http://jsfiddle.net/6vXZH/2/
var last, colours = ['#ff5a5a', '#ffbe0d', '#00ddb8'];
$('.row').each(function() {
var color = colours.splice(~~(Math.random()*colours.length), 1)[0];
$(this).css('background-color', color);
last && colours.push(last), last = color;
});
希望这有帮助!如果您愿意的话,我很乐意为您提供游戏。
使用小数组魔法,无需内循环(http://jsfiddle.net/6vXZH/1/) -
var colours = ['#ff5a5a', '#ffbe0d', '#00ddb8'];
var used = [];
// for each section
$('.row').each(function(i){
var color = colours.splice(~~(Math.random()*colours.length), 1)[0];
$(this).css('background-color', color);
used.push(color);
if(used.length > 1) {
colours.push(used.shift());
}
});
答案 2 :(得分:0)
在函数更好之前定义next和last。
var next=last=Math.floor(Math.random()*3);
$divs.each(function(i){
do {
next = Math.floor(Math.random()*3);
} while( next === last );
$(this).css('background-color', colours[next] );
next = last;
});
答案 3 :(得分:0)
{
var colours = ['#FF5A5A', '#FFBE0D', '#00DDB8'],
divs = $('.row'),
coloursSize = colours.length,
last,
next;
divs.each(function(i){
// get a random colour
do {
next = Math.floor( Math.random() * coloursSize );
// if it's the same as the last one, try again!
} while( next === last )
// when it's different to the last one, set it
$(this).css('background-color', colours[next] );
// tell it this is the last one now
last = next;
});
}