1

我将随机背景颜色(来自 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;

});

有任何想法吗?

4

4 回答 4

2

这是一种语法错误——你无法决定是想要一个 do-while-loop 还是一个普通的 while-loop?您放在那里的内容将被解释为一个简单的

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] );
于 2013-10-25T13:01:29.390 回答
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());
  }
});
于 2013-10-25T13:10:02.647 回答
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;
});
于 2013-10-25T13:05:13.527 回答
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;

});

}

于 2013-10-25T13:30:42.513 回答