我正在尝试使其具有一个颜色,以便在用户单击“随机化”按钮后将其悬停在每个正方形上时使用不同的颜色。当我选择随机函数时,什么都没有改变。这是我的代码:

function randomSetup(numOfSquares){

    var numSquares = numOfSquares;
    var squareSide = 500 / numSquares;
    var totalSquares = numSquares * numSquares;


    for(var rows = 0; rows < totalSquares; rows++){
    $('<div class="gridSquare"></div>').appendTo('.container')
    }

    var colors = randomColor();

    $('.container').on('mouseenter', '.gridSquare', function(){
        $(this).css('background-color', 'rgb(colors,colors,colors)');
    });

    $('.gridSquare').width(squareSide);
    $('.gridSquare').height(squareSide);

}

function randomColor(){

    return Math.random() * (255 - 0) + 1;
}


Fiddle

最佳答案

在这里您可以:http://jsfiddle.net/oLonz7c0/7/

真是的

重新生成事件处理程序中的随机颜色,以便每个正方形都是不同的颜色。

$('.container').on('mouseenter', '.gridSquare', function(){

    var colors = [];
    colors[0] = Math.round(randomColor());
    colors[1] = Math.round(randomColor());
    colors[2] = Math.round(randomColor());

    $(this).css('background-color', 'rgb('+colors[0]+','+colors[1]+','+colors[2]+')');
});

09-30 22:23
查看更多