尝试将按钮背景设置为数组中的随机颜色

时间:2014-02-07 06:31:01

标签: javascript html css background-color

我是新手,我正在尝试创建一个HTML页面,其中的按钮具有基于数组中颜色的随机背景颜色。这就是我现在所拥有的(尽管它不起作用)。我希望有人可以就如何解决这个问题向我提出建议,以便它做到我想要的。

    #button {
            width: 100px;
            height: 100px;
        }

    </style>
</head>

<body>
    <div id="testForm">
        <button id="button">
            Testing
        </button>
    </div>


    <script type="text/javascript">

        $(document).ready(function()
        {
            var myColors = new Array();
            myColors[0] = "#2672EC";
            myColors[1] = "#97009F";
            myColors[2] = "#094DB5";
            myColors[3] = "#00A300";
            myColors[4] = "#DA532C";
            myColors[5] = "#AF1A3F";
            myColors[6] = "#613CBC";
            myColors[7] = "#008AD2";

            var rand = Math.floor(Math.random()*myColors.length); 
            $('#button').css("background-color", myColors[rand]); 
        }


    </script>

2 个答案:

答案 0 :(得分:1)

var myArray = [ "#97009F","#094DB5","#00A300","#DA532C","#AF1A3F","#613CBC","#008AD2"];
var rand = myArray[Math.floor(Math.random() * myArray.length)];

答案 1 :(得分:0)

关闭就绪功能

<强> DEMO

 $(document).ready(function()
            {
                var myColors = new Array();
                myColors[0] = "#2672EC";
                myColors[1] = "#97009F";
                myColors[2] = "#094DB5";
                myColors[3] = "#00A300";
                myColors[4] = "#DA532C";
                myColors[5] = "#AF1A3F";
                myColors[6] = "#613CBC";
                myColors[7] = "#008AD2";

                var rand = Math.floor(Math.random()*myColors.length); 
                $('#button').css("background-color", myColors[rand]); 
            });  //missed to close