Cross-browser (IE8-) getComputedStyle with Javascript?

后端 未结 5 1399
太阳男子
太阳男子 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:25

    This was too big for an edit, so it was made an answer but it doesn't provide a full answer to the question at hand.


    Gabriel's answer fails with a property like "backgroundColor" or "background-color" depending on the browser version because .getPropertyValue expects the CSS property name and el.currentStyle[prop] needs the camel-case version.

    Here's a fixed version which always expects the camel-case version:

    function getStyle(el, prop) {
        return (typeof getComputedStyle !== 'undefined' ?
            getComputedStyle(el, null) :
            el.currentStyle
        )[prop]; // avoid getPropertyValue altogether
    }
    

提交回复
热议问题