js implements the method of setting random background color for Div layer after clicking the button

  • 2020-06-03 05:54:37
  • OfStack

This article shows how js implements the method of setting random background color for Div layer after clicking the button. Share to everybody for everybody reference. The details are as follows:

Set a random background color for myDiv and assign a random color code to the background color for DIV

<!DOCTYPE html>
<meta http-equiv="content-type" content="text/html; charset=gb2312"/>
<title>js Set random colors  </title> 
<script type="text/javascript">
 function getcl(){
 var arr = []// define 1 An empty array 
 i =0;// for while Circular definition i The initial value of the 
 C = '0123456789ABCDEF';
 // A string that defines the color code 
 while(i++ < 6){// cycle 6 time 
 // take 0-16 Between random Numbers given to variables x
 b=parseInt(x);// take 0-16 The previous integer is given to the variable b
 // By the first b ( 0-16 Between the integer bits start to take 1 A character 
 // through 6 The secondary loop gets the random position obtained by combining the characters in 1 Give the minimum value to arr The array 
 var cl = "#"+ arr.join('');
 // Remove the commas between the previous arrays and add them in front 1 A well, 
 // This generates a random color code and assigns the color code to the variable cl
 return cl;// the cl Is returned to the function getcl()
 // The output cl test 1 The results of 
 // So let's start with div The background color assignment for 
 function setColor(){
 // new 1 A function to set the color setColor
 document.getElementById("myDiv").style.backgroundColor = getcl();
 // Assign to the random color code obtained above DIV Background color 
<div id="myDiv" style="width:200px;height:200px;"></div>
<input type="button" value=" to myDiv Set random background color " 
onclick="setColor()" />

Hopefully, this article has been helpful in your javascript programming.

Related articles: