javascript设置颜色值的几种方法

266 阅读2分钟

1、英文命令颜色

p{color:red;}

2、RGB颜色

这个与 `photoshop` 中的 `RGB` 颜色是一致的,由 `R(red)`、`G(green)`、`B(blue)`三种颜色的比例来配色。如:
p{color:rgb(133,45,200);}每一项的值可以是 0~255 之间的整数,也可以是 0%~100% 的百分数。如:`
p{color:rgb(20%,33%,25%);} RGB的第四个参数是透明度,取值为0-1

3、十六进制颜色

这种颜色设置方法是现在比较普遍使用的方法,其原理其实也是 RGB 设置,但是其每一项的值由 0-255 变成了十六进制 00-ff。如:
p{color:#00ffff;}

4、hsla颜色值

hsla(360, 50%, 50%, .5) 半透明红色 , 此方式ie8及以下不兼HSLA(H,S,L,A)

H:Hue(色调)。0(或360)表示红色,120表示绿色,240表示蓝色,也可取其他数值来指定颜色。取值为:0 - 360

S:Saturation(饱和度)。取值为:0.0% - 100.0%

L:Lightness(亮度)。取值为:0.0% - 100.0%

A:Alpha透明度。取值0~1之间。

生成随机颜色代码:

方法一:RGB颜色
	function RandomColor1(){
			return '#'+Math.floor(Math.random()*255).toString(10)
	}
方法二:十六进制颜色
	function RandomColor2(){
			return'#'+Math.floor(Math.random()*0xffffff).toString(16)
	}
方法三:
	使用RGB来表示,并使用es6语法,使用RGB的好处,一是代码少,简单好实现;二是可以支持透明度,透明度也可以支持随机颜色
	function RandomColor3 () {
            const r = Math.round(Math.random()*255);
			const g = Math.round(Math.random()*255);
			const b = Math.round(Math.random()*255);
			//随机颜色返回的是一个0.5到1 的两位小数;如果生成的0-1就直接是
			const a = ( (Math.random()*5 + 5) / 10 ).toFixed(2)		
			const a =Math.random()
			const color = `rgba(${r},${g},${b},${a})`
			console.log(color)
			return color
	}

方法四:
	function RandomColor4 (){
			//随机一个32的4次幂然后取整,这个值接近fffff的十进制
			var random=parseInt(Math.random()*Math.pow(32,4));
			var v=('00000'+random.toString(16)).substr(-4);
			//random返回一个位数不确定的整数,然后toString(16)转化成16进制,
			//如果这个随机数位数不够四位的话前边拼接5个0,最后截取后四位
			return v;
	}

方法五:
	function RandomHColor5() { 
			//随机生成十六进制颜色
		var hex = Math.floor(Math.random() * 16777216).toString(16); 
			//生成ffffff以内16进制数
			while (hex.length < 6) {
				//while循环判断hex位数,少于6位前面加0凑够6位
				hex = '0' + hex;
			}
			return '#' + hex; //返回‘#'开头16进制颜色
	}

本文链接:www.ngui.cc/51cto/show-…