跨浏览器(IE8-)getComputedStyle与Javascript? [英] Cross-browser (IE8-) getComputedStyle with Javascript?

查看:139
本文介绍了跨浏览器(IE8-)getComputedStyle与Javascript?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于 IE8 不支持 getComputedStyle ,因此我们只能使用 currentStyle 。但是,它不会为某些属性返回真正的计算值。

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

例如:

<style type="text/css">
#div {/* no properties are defined here */}
</style>



<div id="div">div</div>



// returns "medium" instead of 0px
document.getElementById('div').currentStyle.borderLeftWidth

// returns "auto" instead of 0px
document.getElementById('div').currentStyle.marginLeft

// returns "undefined" instead of 1
document.getElementById('div').currentStyle.opacity

有没有人使用跨浏览器解决方案的所有属性,而不使用jQuery或其他Javascript库?

Does anyone have a cross-browser solution for all properties without using jQuery or other Javascript libraries?

推荐答案

你不想使用jquery,但没有什么阻止你偷看代码,看看它们是如何处理的: - )

You don't want to use jquery but there's nothing preventing you from peeking into the code and see how they dealt with it :-)

在jQuery代码中,有一个关于此评论的参考到点(阅读全文)。
这里是应该处理你的问题的jquery代码:

Inside jquery code there's a reference about this comment which seems to the point (read also the whole article). Here's the jquery code that should deal with your problem:

else if ( document.documentElement.currentStyle ) {
    curCSS = function( elem, name ) {
        var left, rsLeft,
            ret = elem.currentStyle && elem.currentStyle[ name ],
        style = elem.style;

    // Avoid setting ret to empty string here
    // so we don't default to auto
    if ( ret == null && style && style[ name ] ) {
        ret = style[ name ];
    }

    // From the awesome hack by Dean Edwards
    // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291

    // If we're not dealing with a regular pixel number
    // but a number that has a weird ending, we need to convert it to pixels
    // but not position css attributes, as those are proportional to the parent element instead
    // and we can't measure the parent instead because it might trigger a "stacking dolls" problem
    if ( rnumnonpx.test( ret ) && !rposition.test( name ) ) {

        // Remember the original values
        left = style.left;
        rsLeft = elem.runtimeStyle && elem.runtimeStyle.left;

        // Put in the new values to get a computed value out
        if ( rsLeft ) {
            elem.runtimeStyle.left = elem.currentStyle.left;
        }
        style.left = name === "fontSize" ? "1em" : ret;
        ret = style.pixelLeft + "px";

        // Revert the changed values
        style.left = left;
        if ( rsLeft ) {
            elem.runtimeStyle.left = rsLeft;
        }
    }

    return ret === "" ? "auto" : ret;
};
}

这篇关于跨浏览器(IE8-)getComputedStyle与Javascript?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆