本文实例讲述了JavaScript实现简单生成随机颜色的方法。分享给大家供大家参考,具体如下:
如果要做出如下效果,每次刷新网页则产生一种颜色
[img]http://files.jb51.net/file_images/article/201709/2017921121520583.gif?2017821121546[/img]
其实非常简单,产生随机颜色的根本核心就是随机构造出一个六位数,JavaScript的随机数的问题
而且这个六位数的每一个数位0~f之内,因此就有了如下的方法:
1、首先是一个HTML布局,p标签是是用来放当前颜色的,div的背景颜色就是这个颜色
<!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>
<div id="div1" style="width:100px;height:100px"></div>
</body>
</html>
2、之后是核心的脚本:
<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("div1").style.backgroundColor="#"+colorStr;
</script>
[b]PS:这里再为大家提供几款功能类似的在线工具供大家参考:[/b]
[b]在线随机数字/字符串生成工具:
[/b][url=http://tools.jb51.net/aideddesign/suijishu]http://tools.jb51.net/aideddesign/suijishu[/url]
[b]在线随机字符/随机密码生成工具:
[/b][url=http://tools.jb51.net/aideddesign/rnd_password]http://tools.jb51.net/aideddesign/rnd_password[/url]
[b]在线RGB、HEX颜色代码生成器:
[/b][url=http://tools.jb51.net/color/rgb_color_generator]http://tools.jb51.net/color/rgb_color_generator[/url]
[b]RGB颜色查询对照表_颜色代码表_颜色的英文名称大全:
[/b][url=http://tools.jb51.net/color/jPicker]http://tools.jb51.net/color/jPicker[/url]
更多关于JavaScript相关内容感兴趣的读者可查看本站专题:《[url=http://www.1sucai.cn/Special/119.htm]JavaScript数学运算用法总结[/url]》、《[url=http://www.1sucai.cn/Special/297.htm]JavaScript数据结构与算法技巧总结[/url]》、《[url=http://www.1sucai.cn/Special/278.htm]JavaScript数组操作技巧总结[/url]》、《[url=http://www.1sucai.cn/Special/148.htm]JavaScript排序算法总结[/url]》、《[url=http://www.1sucai.cn/Special/281.htm]JavaScript遍历算法与技巧总结[/url]》、《[url=http://www.1sucai.cn/Special/472.htm]JavaScript查找算法技巧总结[/url]》及《[url=http://www.1sucai.cn/Special/439.htm]JavaScript错误与调试技巧总结[/url]》
希望本文所述对大家JavaScript程序设计有所帮助。