代码改变世界

【javascript】Convert any colour value to hex in MSIE

2012-07-12 14:07  sniper007  阅读(214)  评论(0编辑  收藏  举报
The following function will convert any colour value (rgb, named colours, etc) to the hex equivalent in MSIE:

function toHex(color) {
  var body  = createPopup().document.body,
      range = body.createTextRange();
  body.style.color = color;
  var value = range.queryCommandValue("ForeColor");
  value = ((value & 0x0000ff) << 16) | (value & 0x00ff00) | ((value & 0xff0000) >>> 16);
  value = value.toString(16);
  return "#000000".slice(0, 7 - value.length) + value;
};
For other browsers you can use getComputedStyle() so that is already a solved problem.