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

js method to set random background color to Div layer after clicking button_javascript skills

WBOY
Release: 2016-05-16 16:00:48
Original
1696 people have browsed it

The example in this article describes the js method of setting a random background color to the Div layer after clicking the button. Share it with everyone for your reference. The details are as follows:

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

<!DOCTYPE html>
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=gb2312"/>
<title>js设置随机颜色 </title> 
</head>
<body>
<script type="text/javascript">
 function getcl(){
 var arr = []//定义一个空的数组
 i =0;//为while循环定义i的初始值
 C = '0123456789ABCDEF';
 //定义颜色代码的字符串
 while(i++ < 6){//循环6次
 x=Math.random()*16;
 //取0-16之间的随机数给变量x
 b=parseInt(x);//取0-16之前的整数给变量b
 c=C.substr(b,1);
 //由第b(0-16之间的整数)位开始取一个字符
 arr.push(c);
 //通过6次循环得到的随机位置取得的字符组合在一起把值给到arr这个数组
 }
 var cl = "#"+ arr.join('');
 //去掉之前数组之间的逗号,前面再加一个井号,
 //这样颜色随机的颜色代码就生成了,并且把颜色代码赋值给变量cl
 return cl;//把cl的值返回给函数getcl()
 }
document.write(cl);
 //输出cl测试一下结果
 //下面开始给div的背景颜色赋值
 function setColor(){
 //新建一个设置颜色的函数setColor
 document.getElementById("myDiv").style.backgroundColor = getcl();
 //把上面得到的随机颜色代码赋值给DIV的背景颜色
 } 
</script>
<div id="myDiv" style="width:200px;height:200px;"></div>
<input type="button" value="给myDiv设置随机背景颜色" 
onclick="setColor()" />
</body>
</html>
Copy after login

I hope this article will be helpful to everyone’s JavaScript programming design.

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