get computed background color as rgb in IE

前端 未结 1 1459
没有蜡笔的小新
没有蜡笔的小新 2021-01-22 05:36

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[nam         


        
相关标签:
1条回答
  • 2021-01-22 06:22

    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.

    0 讨论(0)
提交回复
热议问题