css的16进制颜色转换成rgb 并且可以设置透明度rgba; rgb转换成16进制。

 16进制转换成rgb 

hexToRgb(hexStr) {
				//十六进制颜色值的正则表达式
				let reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
				let sColor = hexStr.toLowerCase();
				if (sColor && reg.test(sColor)) {
					if (sColor.length === 4) {
						let sColorNew = "#";
						for (let i = 1; i < 4; i += 1) {
							sColorNew += sColor.slice(i, i + 1).concat(sColor.slice(i, i + 1));
						}
						sColor = sColorNew;
					}
					//处理六位的颜色值f
					let sColorChange = [];
					for (let i = 1; i < 7; i += 2) {
						sColorChange.push(parseInt(`0x${sColor.slice(i, i + 2)}`));
					}
					let rgbText = sColorChange.join(",")
					return rgbText;
				} else {
					return sColor;
				}
			},

 rgb转换成 16进制

rgbToHex(rgbStr){
    //十六进制颜色值的正则表达式
    const reg = /^#([0-9a-fA-f]{3}|[0-9a-fA-f]{6})$/;
    if (/^(rgb|RGB)/.test(rgbStr)) {
        const aColor = rgbStr.replace(/(?:\(|\)|rgb|RGB)*/g, "").split(",");
        let strHex = "#";
        for (let i = 0; i < aColor.length; i++) {
            let hex = Number(aColor[i]).toString(16).padStart(2,0);
            if (hex === "0") {
                hex += hex;
            }
            strHex += hex;
        }
        if (strHex.length !== 7) {
            strHex = rgbStr;
        }
        return strHex;
    } else if (reg.test(rgbStr)) {
        const aNum = rgbStr.replace(/#/, "").split("");
        if (aNum.length === 6) {
            return rgbStr;
        } else if (aNum.length === 3) {
            let numHex = "#";
            for (let i = 0; i < aNum.length; i += 1) {
                numHex += (aNum[i] + aNum[i]);
            }
            return numHex;
        }
    } else {
        return rgbStr;
    }
},

使用

background: linear-gradient(to right, rgba(var(--mian_color_rgb), 0.3), rgba(var(--secondary_color_rgb), 0.3));

你可能感兴趣的:(css,前端)