Random colors have two formats:
Effect preview: http://wjf444128852.github.io/DEMOLIST/JS/test/index.html
1, RGB (XXX,XXX,XXX)
2, #xxxxxx
Implement two methods of randomization
thinking: How to make x random,
1, XXX is a random integer between 0-255, using Math.random () *255 to obtain a random number between 0-255,
then Math.floor () retains the
2 before the decimal point, X in the 0123456789abxdef is a combination of random 6,
here can be used array or string processing, where the array, as long as from the array 6 times, each get the array subscript is 0-16 between the random integer.
Note (although #xxxx is changed in Law II, the browser looks at the Background-color property value of the DOM element or RGB format, but the assignment in JS is # XXX format.
Code is as follows:
html
<body>
<div class= "main" >
<p><a href= "javascript:;" id= "Btn-one" >randomcolor-rgb </a></p>
<ul>
<li><div class= "Bg_color" ></div></li>
< Li><div class= "Bg_color" ></div></li>
<li><div class= "Bg_color" ></div> </li>
<li><div class= "Bg_color" ></div></li>
</ul>
</div>
<div class= "main" >
<p><a href= "javascript:;" id= "Btn-two" >randomcolor-#XXXXXX </a ></p>
<ul>
<li><div class= "Bg_two" ></div></li>
<li> <div class= "Bg_two" ></div></li>
<li><div class= "Bg_two" ></div></li >
<li><div class= "Bg_two" ></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;
}
P a{
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-colored functions-rgb functional Getrandomcolor () {var rgb= ' rgb (' +math.floor ') (Math.rand
Om () *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 #xxxxxx 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 the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.