在IE中将计算出的背景颜色作为rgb

我试图使用以下代码在IE中获取RGB背景颜色:

function getStyle(elem, name) { // J/S Pro Techniques p136 if (elem.style[name]) { return elem.style[name]; } else if (elem.currentStyle) { return elem.currentStyle[name]; } else if (document.defaultView && document.defaultView.getComputedStyle) { name = name.replace(/([AZ])/g, "-$1"); name = name.toLowerCase(); s = document.defaultView.getComputedStyle(elem, ""); return s && s.getPropertyValue(name); } else { return null; } } var $b = $("

这不会像firefox那样返回rgb颜色值,它返回’buttonface’,这对我来说是无用的。

我一直在研究“getStyle”函数的跨浏览器实现,我的function尚未完成,但我可以帮助您解决IE中的这个特定问题。

对于计算出的backgroundColor ,我使用的是本页提出的hack,它使用IE特定的queryCommandValue方法来获取选择的BackColor

关于你发布的实现,我建议首先检查是否存在通过document.defaultView的标准getComputedStyle方法,因为像Opera这样的浏览器提供了IE特定的currentStyle对象以实现兼容性。

所以我重构了你的function并包含了IE hack

 function getStyle(elem, name) { if (document.defaultView && document.defaultView.getComputedStyle) { name = name.replace(/([AZ])/g, "-$1"); name = name.toLowerCase(); s = document.defaultView.getComputedStyle(elem, ""); return s && s.getPropertyValue(name); } else if (elem.currentStyle) { if (/backgroundcolor/i.test(name)) { return (function (el) { // get a rgb based color on IE var oRG=document.body.createTextRange(); oRG.moveToElementText(el); var iClr=oRG.queryCommandValue("BackColor"); return "rgb("+(iClr & 0xFF)+","+((iClr & 0xFF00)>>8)+","+ ((iClr & 0xFF0000)>>16)+")"; })(elem); } return elem.currentStyle[name]; } else if (elem.style[name]) { return elem.style[name]; } else { return null; } } 

希望很快我会发布一个更通用的实现,但这足以解决你的backgorundColor问题。

您可以在此处测试上述function。