This article mainly introduces the method of simply generating random colors in JavaScript, involving implementation techniques related to JavaScript random numbers and string operations and dynamic operations of page element attributes. Friends in need can refer to the examples of this article
Describes how to simply generate random colors using JavaScript. Share it with everyone for your reference, the details are as follows:
If you want to make the following effect, each time you refresh the web page, a color will be generated
It is actually very simple , the fundamental core of generating random colors is to randomly construct a six-digit number, JavaScript's random number problem
And each digit of this six-digit number is within 0~f, so there is the following method :
1. First is an HTML layout. The p tag is used to put the current color. The background color of p is this color
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> <title>randomColor</title> </head> <body> <p id="colorStr"></p> <p id="p1" style="width:100px;height:100px"></p> </body> </html>
2 , followed by the core script:
<script> //颜色字符串 var colorStr=""; //字符串的每一字符的范围 var randomArr=['0','1','2','3','4','5','6','7','8','9','a','b','c','d','e','f']; //产生一个六位的字符串 for(var i=0;i<6;i++){ //15是范围上限,0是范围下限,两个函数保证产生出来的随机数是整数 colorStr+=randomArr[Math.ceil(Math.random()*(15-0)+0)]; } document.getElementById("colorStr").innerHTML="颜色为:#"+colorStr; document.getElementById("p1").style.backgroundColor="#"+colorStr; </script>
The above is the detailed content of How to implement random colors using JavaScript. For more information, please follow other related articles on the PHP Chinese website!