Search code examples
javascriptjquerycomputed-style

get computed background color as rgb in IE


I am trying to get the RGB background color in IE using the following code:

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'

this does not return an rgb color value like firefox does, it returns 'buttonface' which is useless to me.


Solution

  • I have been working on a cross-browser implementation of a "getStyle" function, my function isn't complete yet but I can help you to solve this specific problem you have with IE.

    For the computed backgroundColor, I'm using a hack proposed in this page, it uses the IE specific queryCommandValue method to get the BackColor of a selection.

    About the implementation you post, I would recommend to check first if the standard getComputedStyle method via the document.defaultView exists, because some browsers like Opera, provide the IE specific currentStyle object for compatibility.

    So I've refactored your function and included the 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;
      }
    }
    

    Hopefully soon I'll post a more generic implementation, but this will be enough to solve your backgorundColor issue.

    You can test the above function here.