我刚刚使用 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/