Home > Web Front-end > JS Tutorial > body text

A simple way to generate random colors using JavaScript

小云云
Release: 2018-02-07 11:23:43
Original
2863 people have browsed it

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>
Copy after login

2. Next is the core script:


<script>
  //颜色字符串
  var colorStr="";
  //字符串的每一字符的范围
  var randomArr=[&#39;0&#39;,&#39;1&#39;,&#39;2&#39;,&#39;3&#39;,&#39;4&#39;,&#39;5&#39;,&#39;6&#39;,&#39;7&#39;,&#39;8&#39;,&#39;9&#39;,&#39;a&#39;,&#39;b&#39;,&#39;c&#39;,&#39;d&#39;,&#39;e&#39;,&#39;f&#39;];
  //产生一个六位的字符串
  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>
Copy after login

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!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!