javascript - 如何根据当前颜色生成相反的颜色?

标签 javascript jquery html css colors

我正在尝试创建一种与当前颜色相反的颜色。我的意思是如果当前颜色是黑色,那么我需要生成白色

其实我有一个文本(这个文本的颜色是动态的,它的颜色可以随机生成)。该文本位于 div 中,我需要为 divbackground-color 设置与该文本相反的颜色。我希望 div (颜色透视) 中的文本清晰

The opposite color means: Dark / Bright

我有文本的当前颜色,我可以将它传递给这个函数:

var TextColor = #F0F0F0;    // for example (it is a bright color)

function create_opp_color(current color) {

    // create opposite color according to current color

}

create_opp_color(TextColor); // this should be something like "#202020" (or a dark color)

是否有创建 create_opp_color() 函数的想法?

最佳答案

更新:生产就绪代码在GitHub .


我会这样做:

  1. 将 HEX 转换为 RGB
  2. 反转 R、G 和 B 分量
  3. 将每个组件转换回十六进制
  4. 用零填充每个组件并输出。
function invertColor(hex) {
    if (hex.indexOf('#') === 0) {
        hex = hex.slice(1);
    }
    // convert 3-digit hex to 6-digits.
    if (hex.length === 3) {
        hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2];
    }
    if (hex.length !== 6) {
        throw new Error('Invalid HEX color.');
    }
    // invert color components
    var r = (255 - parseInt(hex.slice(0, 2), 16)).toString(16),
        g = (255 - parseInt(hex.slice(2, 4), 16)).toString(16),
        b = (255 - parseInt(hex.slice(4, 6), 16)).toString(16);
    // pad each with zeros and return
    return '#' + padZero(r) + padZero(g) + padZero(b);
}

function padZero(str, len) {
    len = len || 2;
    var zeros = new Array(len).join('0');
    return (zeros + str).slice(-len);
}

示例输出:

enter image description here

进阶版:

这有一个 bw 选项,它将决定是反转为黑色还是白色;这样您将获得更多对比度,这通常对人眼来说更好。

function invertColor(hex, bw) {
    if (hex.indexOf('#') === 0) {
        hex = hex.slice(1);
    }
    // convert 3-digit hex to 6-digits.
    if (hex.length === 3) {
        hex = hex[0] + hex[0] + hex[1] + hex[1] + hex[2] + hex[2];
    }
    if (hex.length !== 6) {
        throw new Error('Invalid HEX color.');
    }
    var r = parseInt(hex.slice(0, 2), 16),
        g = parseInt(hex.slice(2, 4), 16),
        b = parseInt(hex.slice(4, 6), 16);
    if (bw) {
        // https://stackoverflow.com/a/3943023/112731
        return (r * 0.299 + g * 0.587 + b * 0.114) > 186
            ? '#000000'
            : '#FFFFFF';
    }
    // invert color components
    r = (255 - r).toString(16);
    g = (255 - g).toString(16);
    b = (255 - b).toString(16);
    // pad each with zeros and return
    return "#" + padZero(r) + padZero(g) + padZero(b);
}

示例输出:

enter image description here

关于javascript - 如何根据当前颜色生成相反的颜色?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35969656/

相关文章:

javascript - 手机版网站滑动功能

javascript - 使用 JS 选择外部 CSS 文件

javascript - html javascript 搜索不工作

javascript - 如何在处理节点时设置ag-Grid中的单元格样式?

javascript - jquery find 只返回一个元素(在 Meteor 中)

html - 固定位置使元素的代码部分消失

asp.net - 视频标签不适用于移动设备

javascript - 使用 Javascript 获取选择输入并在另一部分使用数据

jquery - 如何直接从浏览器使用外部 Sparql 请求的 json 输出?

javascript - 在 jQuery 切片后重新 append 列表项并删除