复制代码
代码如下:
function
getRandomColor(){
return
"#"+("00000"+((Math.random()*16777215+0.5)>>0).toString(16)).slice(-6)
}
说明:
1、16777215为16进制的颜色ffffff转成10进制的数字
2、>>数字取整
3、转成16进制不足6位的以0来补充
在线演示代码:
js随机颜色
document.writeln('#'+('00000'+(Math.random()*0x1000000
昨天在做js从10种颜色中随机取色,并每次取出的颜色不同的时候,考虑了很多,最终用如下来实现:
复制代码
代码如下:
var
colorList
=
["#FFFF99","#B5FF91","#94DBFF","#FFBAFF","#FFBD9D","#C7A3ED","#CC9898","#8AC007","#CCC007","#FFAD5C"]
for(var
i=0i<lineList.lengthi++){
var
bgColor
=
getColorByRandom(colorList)
}
function
getColorByRandom(colorList){
var
colorIndex
=
Math.floor(Math.random()*colorList.length)
var
color
=
colorList[colorIndex]
colorList.splice(colorIndex,1)
return
color
}
这样便能每次取出的颜色是随机的且都不一样
实现思路是取一个随机数,颜色值保存在数组中,然后依次给标签css样式赋值
<!DOCTYPE html><html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<p>颜色</p>
<p>颜色</p>
<p>颜色</p>
<p>颜色</p>
<p>颜色</p>
<script>
let color = [' #000000', '#FF0000', '#00FF00', '#0000FF', '#FFFF00']
function random() {
let i = Math.floor(Math.random() * (color.length - 1))
let text = color.splice(i, 1)[0]
return text
}
let p = document.getElementsByTagName('p')
for (let i = 0 i < p.length i++) {
p[i].style.color = random()
}
</script>
</body>
</html>