Cross-browser (IE8-) getComputedStyle with Javascript?

后端 未结 5 1392
太阳男子
太阳男子 2020-11-28 10:58

Since IE8 does not support getComputedStyle, we can only use currentStyle. However, it does not return the real \"computed\" value

5条回答
  •  谎友^
    谎友^ (楼主)
    2020-11-28 11:06

    Here's a cross-browser function to get a computed style...

    getStyle = function (el, prop) {
        if (typeof getComputedStyle !== 'undefined') {
            return getComputedStyle(el, null).getPropertyValue(prop);
        } else {
            return el.currentStyle[prop];
        }
    }
    

    You may store it as an utility within an object, or just use it as provided. Here's a sample demo!

    // Create paragraph element and append some text to it
    var p = document.createElement('p');
    p.appendChild(document.createTextNode('something for fun'));
    
    // Append element to the body
    document.getElementsByTagName('body')[0].appendChild(p);
    
    // Set hex color to this element
    p.style.color = '#999';
    
    // alert element's color using getStyle function
    alert(getStyle(p, 'color'));
    

    Check this demo to see it in action:

    getStyle = function(el, prop) {
      if (getComputedStyle !== 'undefined') {
        return getComputedStyle(el, null).getPropertyValue(prop);
      } else {
        return el.currentStyle[prop];
      }
    }
    
    // Create paragraph element and append some text to it
    var p = document.createElement('p');
    p.appendChild(document.createTextNode('something for fun'));
    
    // Append element to the body
    document.getElementsByTagName('body')[0].appendChild(p);
    
    // Set hex color to this element
    p.style.color = '#999';
    
    // alert element's color using getStyle function
    console.log(getStyle(p, 'color'));
    p {
      color: red;
    }

提交回复
热议问题