js实现颜色
使用 JavaScript 操作颜色的方法
通过十六进制字符串表示颜色
JavaScript 可以直接使用十六进制字符串表示颜色:
const colorHex = '#FF5733';
使用 RGB 或 RGBA 值
通过 rgb() 或 rgba() 函数创建颜色:
const colorRGB = 'rgb(255, 87, 51)';
const colorRGBA = 'rgba(255, 87, 51, 0.5)';
使用 HSL 或 HSLA 值
HSL(色相、饱和度、亮度)格式:
const colorHSL = 'hsl(12, 100%, 60%)';
const colorHSLA = 'hsla(12, 100%, 60%, 0.5)';
动态生成随机颜色
生成随机十六进制颜色:

function getRandomColor() {
return `#${Math.floor(Math.random() * 16777215).toString(16)}`;
}
颜色转换功能
将 RGB 转换为十六进制:
function rgbToHex(r, g, b) {
return `#${[r, g, b].map(x => x.toString(16).padStart(2, '0')).join('')}`;
}
修改 DOM 元素颜色
通过 JavaScript 改变元素颜色:

document.getElementById('myElement').style.color = '#FF5733';
document.querySelector('.myClass').style.backgroundColor = 'rgba(255, 87, 51, 0.5)';
使用颜色库
对于更复杂的颜色操作,可以使用专业库:
// 使用 TinyColor 库
const tinyColor = new TinyColor('#FF5733');
const lightened = tinyColor.lighten(10).toString();
检测颜色对比度
计算两种颜色的对比度(用于可访问性检查):
function getContrastRatio(color1, color2) {
const luminance1 = getLuminance(color1);
const luminance2 = getLuminance(color2);
return (Math.max(luminance1, luminance2) + 0.05) / (Math.min(luminance1, luminance2) + 0.05);
}
颜色渐变实现
创建线性渐变:
const gradient = 'linear-gradient(to right, #FF5733, #33FF57)';
document.getElementById('gradientElement').style.background = gradient;






