Picking a random color from array

This question already has an answer here:

  • Change an element's class with JavaScript 30 answers

  • To use a javascript variable as an HTML value, you have to set it in javascript. So to set your value attribute, do it like this: And you need to wrap the code in the function that you set in the onClick

    <script>
        function addObject(){    
           var colorArray = ['.st1', '.st2', '.st3', '.st4'];
            var randomColor = Math.floor(Math.random() * colorArray.length);
            console.log(colorArray[randomColor]);
            document.getElementById("new-class").className = colorArray[randomColor];
        }
    </script>
    
    链接地址: http://www.djcxy.com/p/25216.html

    上一篇: 如何在ul标签中添加一个类属性

    下一篇: 从阵列中选取随机颜色