JavaScript。求十六进制代码的反码

标签 javascript html hex inverse

我刚刚使用 HTML 十六进制颜色代码,想知道是否有任何简单的方法可以使用计划 javascript 计算任何颜色代码的逆。

const hex = "#xxxxxx";
const inverseHex = "#yyyyyy";

const add = hex + inverseHex; // #000000

最佳答案

我的 50 美分:

const inv = (hex) => '#' + hex.match(/[a-f0-9]{2}/ig).map(e => (255 - parseInt(e, 16) | 0).toString(16).replace(/^([a-f0-9])$/, '0$1')).join('')

const invert = () =>
  document.querySelectorAll('circle')
    .forEach(c => 
      (hex = c.getAttribute('fill')) && 
      c.setAttribute('fill', inv(hex))
    )

console.log('#000000', inv('#000000'))
console.log('#ffffff', inv('#ffffff'))
console.log('#ff6600', inv('#ff6600'))
console.log('#fe4289', inv('#fe4289'))
body {
  background: grey
}

svg {
  width: 45px;
  height: 45px;
  display: inline-block;
  margin: 10px
}
<svg><circle cx="20" cy="20" r="20" fill="#000000"/></svg>
<svg><circle cx="20" cy="20" r="20" fill="#ffffff"/></svg>
<svg><circle cx="20" cy="20" r="20" fill="#ff6600"/></svg>
<svg><circle cx="20" cy="20" r="20" fill="#fe4289"/></svg>

<p><button onclick="invert()">Invert!</button></p>

关于JavaScript。求十六进制代码的反码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51568098/

相关文章:

javascript - 如何从 localStorage 中删除对象或数组?

Javascript 将 30 或 20、22 天添加到原始日期?

html - 自动选择 HTML 输入中的文本

c++ - 使用十六进制数字表示法编写代码有什么意义?

javascript - Google 阻止了我的网站 : all *. js 文件被感染。如何找到感染我的 JavaScript 代码的进程?

javascript - 当用户在 Bootstrap 日期选择器中更改月份时动态更新选项

javascript - 嵌入式 youtube 模糊了我的字体。我想知道是什么字体

javascript - 更改另一个 <select> 元素的 <select> onchange 中的元素

hex - 如何用大脑将十六进制转为十进制?

c - 缓冲区溢出将超过 0x7E 的字节添加到堆栈