我将随机背景颜色(来自 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;
});
有任何想法吗?