Random colors are available in two formats:
Effect preview: http://wjf444128852.github.io/DEMOLIST/JS/test/index.html
1. rgb(xxx,xxx,xxx)
2. #xxxxxx
The following two random methods are implemented
Idea: How to make x random
1. The xxx in it is a random integer between 0-255. Use Math.random()*255 to get a random number between 0-255.
Then Math.floor() keeps the decimal point before it
2. The x in it is a random combination of 6 in 0123456789abxdef.
Here you can use an array or a string to process it. Here you use an array. Just take 6 times from the array and get the array subscript is a random integer between 0 and 16 each time.
Note (Although the change in Method 2 is #XXXX, the browser checks the background-color attribute value of the DOM element in this case, but the assignment in JS is in #xxx format.)
The code is as follows:
HTML
<body> <div> <p><a href="javascript:;" id="btn-one">RandomColor-rgb</a></p> <ul> <li><div></div></li> <li><div></div></li> <li><div></div></li> <li><div></div></li> <li><div></div></li> <li><div></div></li> <li><div></div></li> <li><div></div></li> <li><div></div></li> <li><div></div></li> <li><div></div></li> <li><div></div></li> <li><div></div></li> <li><div></div></li> <li><div></div></li> </ul> </div></body>
CSS
*{ box-sizing: border-box; list-style: none; border: none; padding: 0; margin: 0; } p{ text-align: center; margin: 20px; } pa{ font-size: 20px; font-weight: 300; color: #e4393c; text-decoration: none; padding: 6px 10px; border: 1px solid currentColor; } .bg_color,.bg_two{ width: 100px; height: 100px; border: 1px solid #aa00aa; } .main,.main ul{ overflow: hidden; } .main{ width: 400px; margin:30px auto; } .main ul li{ float: left; }JS
<script> (function(){ //1. Random color function -rgb function getRandomColor(){ var rgb='rgb('+Math.floor(Math.random()*255)+',' +Math.floor(Math.random()*255)+',' +Math.floor(Math.random()*255)+',' +Math.floor(Math.random()*255)+')'; console.log(rgb); return rgb; }// Get button var btn_one=document.querySelector("#btn-one"); var Divs=document.querySelectorAll(".bg_color"); btn_one.onclick=function(){ for(var i=0;i<Divs.length;i++){ Divs[i].style.backgroundColor=getRandomColor(); } }; //2. Random color#XXXXX var btn_two=document.querySelector("#btn-two"); var divsTwo=document.querySelectorAll(".bg_two"); var chars = ['0','1','2','3','4','5','6','7','8','9','A','B','C','D','E','F']; function generateMixed(n) { var res = "#"; var id; for(var i = 0; i < n ; i ++) { id= Math.floor(Math.random()*16); res += chars[id]; } console.log(id,res); return res; } btn_two.onclick=function(){ for(var i=0;i<divsTwo.length;i++){ divsTwo[i].style.backgroundColor=generateMixed(6); } }; })()</script>The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.