Home > Web Front-end > JS Tutorial > How to implement random colors using JavaScript

How to implement random colors using JavaScript

黄舟
Release: 2017-09-22 09:18:55
Original
2710 people have browsed it

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

2 , followed by 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

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!

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