This article mainly introduces you to 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 who need it can refer to it. I hope it can help you.
If you want to make the following effect, a color will be generated every time you refresh the web page
It is actually very simple. The fundamental core of generating random colors is random construction The problem of generating a six-digit JavaScript random number
and each digit of this six-digit number is within 0~f, so there is the following method:
1. First, It 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. Next is 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>
Related recommendations:
php simple method to generate random colors
Get random colors The php code
one gets the random color generated in the area
The above is the detailed content of A simple way to generate random colors using JavaScript. For more information, please follow other related articles on the PHP Chinese website!