2
我得到的body
的颜色和背景颜色的计算HEX像这样走:挑选颜色更是从白色
function rgb2hex(rgb){
rgb = rgb.match(/^rgba?[\s+]?\([\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?,[\s+]?(\d+)[\s+]?/i);
return (rgb && rgb.length === 4) ? "#" +
("0" + parseInt(rgb[1],10).toString(16)).slice(-2) +
("0" + parseInt(rgb[2],10).toString(16)).slice(-2) +
("0" + parseInt(rgb[3],10).toString(16)).slice(-2) : '';
}
var color = rgb2hex(window.getComputedStyle(document.getElementsByTagName("body")[0]).color);
var bg = rgb2hex(window.getComputedStyle(document.getElementsByTagName("body")[0]).backgroundColor);
我需要选择其中一种颜色用作文本颜色在白色背景上。但是,页面背景较暗并且颜色较浅/白色时会出现问题。因此,我需要智能地选择其中的一个用作文本颜色。
我如何知道color
和bg
中的哪一个离#fff
最远?
最远在什么意义?你想选择最对比的颜色? – byxor
这完全正确。这两种颜色中的哪一种在视觉上最适合作为文本'color'使用,当'background:#fff;' –
将使用CSS颠倒属性(https://davidwalsh.name/invert-colors-css)做什么你要?它你想要一个JavaScript函数,这是一个搞清楚如何在JavaScript中进行反转的问题。像这样:http://stackoverflow.com/questions/6961725/algorithm-for-calculating-inverse-color – zelite