首页 文章

随机颜色组合(文本/背景)

提问于
浏览
-1

我有15个带文本元素的div,想要跟随:

在每个页面加载时,div-background-color和text-element-color应该变为随机选择的颜色组合 .

我有10个文本 - & - 背景颜色组合:组合-1:文本蓝色/背景颜色青色组合-2:文本黄色/背景颜色粉红色组合-3:文本青色/背景颜色红色组合-4:文字红/背景颜色蓝色等

现在我想要一个jQuery脚本随机给div的颜色组合(text-color和div-background-color) .

请考虑,我不想只是随机颜色,而是随机颜色组合(随机颜色对) .

你能以某种方式帮助我吗?

$(document).ready(function () {
    var back = ["#ff0000","blue","gray", "red", "green", "white"];
    var rand = back[Math.floor(Math.random() * back.length)];
    console.log(rand);
    $('div').css('background',rand);
    $('span').css('color',rand);
    })
div {
    width:200px;
    height:200px;
    background:red;
}
<div>
<span>text</span>
</div>

http://jsfiddle.net/sJTHc/356/(文字和背景总是相同的随机颜色)

我不知道如何解决这个组合事物......

1 回答

  • 0

    这样的事情怎么样:

    var colors = [
        ['blue', 'cyan'],
        ['yellow', 'pink'],
        // etc…
    ];
    
    function getRandomColorCombination(colors) {
        var random = parseInt(Math.random() * colors.length);
    
        return colors[random];
    }
    
    $('div').each(function () {
        var randomColorCombination = getRandomColorCombination(colors);
    
        $(this).css('color', randomColorCombination[0]);
        $(this).css('backgroundColor', randomColorCombination[1]);
    });
    

相关问题