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

时间:2010-03-16 02:46:06

标签: javascript jquery computed-style

我正在尝试使用以下代码在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(/([A-Z])/g, "-$1");
        name = name.toLowerCase();
        s = document.defaultView.getComputedStyle(elem, "");
        return s && s.getPropertyValue(name);
    } else {
        return null;
    }
}

var $b = $("<button>");
$b.css("backgroundColor", "ButtonFace");
$("body").append($b);
alert("button bg color is: "+ getStyle($b[0],"backgroundColor"));
//alerts 'buttonface'

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

1 个答案:

答案 0 :(得分:5)

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

对于计算出的backgroundColor,我正在使用this页面中提出的黑客攻击,它使用特定于IE的queryCommandValue方法来获取选择的BackColor

关于您发布的实现,我建议首先检查标准getComputedStyle方法是否存在document.defaultView,因为某些浏览器(如Opera)提供了IE特定的currentStyle对象兼容性。

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

function getStyle(elem, name) {
  if (document.defaultView && document.defaultView.getComputedStyle) {
    name = name.replace(/([A-Z])/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问题。

您可以测试上述功能here