/** * 获取颜色值 */ const color2RGB = (color) => { if (typeof color !== 'string' || (color.length !== 7 && color.length !== 4)) return [0, 0, 0]; color = color.substr(1); if (color.length === 3) { return color.split('').map(str => parseInt(str + str, 16)); } let result = []; for (let i = 0; i < 6; i += 2) { result.push(parseInt(color.substr(i, 2), 16)); } return result; }
/** * 加深:correctionFactor<0 变亮:correctionFactor>0 -1.0f <= correctionFactor <= 1.0f @colorStr 颜色值:#ff0000 */ const changeColor = (colorStr, correctionFactor) => { let color = color2RGB(colorStr) let red = parseFloat(color[0]); let green = parseFloat(color[1]); let blue = parseFloat(color[2]); if (correctionFactor < 0) { correctionFactor = 1 + correctionFactor; red *= correctionFactor; green *= correctionFactor; blue *= correctionFactor; } else { red = (255 - red) * correctionFactor + red; green = (255 - green) * correctionFactor + green; blue = (255 - blue) * correctionFactor + blue; } if (red < 0) red = 0; if (red > 255) red = 255; if (green < 0) green = 0; if (green > 255) green = 255; if (blue < 0) blue = 0; if (blue > 255) blue = 255; red = parseInt(red); green = parseInt(green); blue = parseInt(blue) return [red, green, blue]; }
第一种方式:
使用rgba()对颜色进行透明度调整, 例如:rgba(0,0,0,0.5)
let color = `rgba(${color2RGB('#FF0000').join(',')},0.1)`;
第二种方式:
使用changeColor方法来计算颜色的加深、变浅度
let color =`rgb(changeColor('#FF0000', -0.4).join(',')},0.1)`;
第三种方式:
使用背景色重叠来实现加深效果
.aa { width: 200px; height: 200px; background-color: #ff0000; position: relative; } .btn { width: 80px; height: 80px; background-color: rgb(0, 0, 0, 0.2); border-radius: 5px; position: absolute; top: 20px; left: 20px; }
<div class='aa'> <div class='btn'>我是浮层按钮</div> </div>