javascript 使用Javascript跨浏览器(IE8-)getComputedStyle?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/15733365/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 01:53:28  来源:igfitidea点击:

Cross-browser (IE8-) getComputedStyle with Javascript?

javascriptinternet-explorercross-browserstyles

提问by user1643156

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

由于IE8不支持getComputedStyle,我们只能使用currentStyle. 但是,它不会返回某些属性的真实“计算”值。

For example:

例如:

<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

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

有没有人在不使用 jQuery 或其他 Javascript 库的情况下为所有属性提供跨浏览器解决方案?

采纳答案by Eugen Mihailescu

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,但没有什么可以阻止您查看代码并查看他们如何处理它:-)

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

在 jquery 代码中,有一个关于此评论的参考,似乎很重要(另请阅读整篇文章)。这是应该处理您的问题的 jquery 代码:

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;
};
}

回答by Gabriel kyabu

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 demoto 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;
}

回答by Eugen Mihailescu

instead of :

代替 :

getComputedStyle !== 'undefined'

it should be :

它应该是 :

typeof getComputedStyle !== 'undefined'

otherwise it would never works.

否则它永远不会工作。

回答by Kyle Falconer

This will not work for all styles but will work for dimensions (which is what I needed).

这不适用于所有样式,但适用于尺寸(这是我需要的)。

Instead of trying to guess what styles are applied, simply use the position in pixels of each of the four sides of a box-like element to calculate the dimensions. This will also work back to IE 5 and FF 3.

不要试图猜测应用了哪些样式,只需使用盒状元素四个边中每一个的像素位置来计算尺寸。这也将适用于 IE 5 和 FF 3。

height = elem.getBoundingClientRect().bottom - elem.getBoundingClientRect().top;
width = elem.getBoundingClientRect().right - elem.getBoundingClientRect().left;

See also: getBoundingClientRect is awesome

另请参阅:getBoundingClientRect 很棒

If this still doesn't work for you, check out this fiddleI put together for calculating the inside width of a box. It uses the following as a shim for getComputedStyle:

如果这仍然不适合您,请查看我放在一起用于计算盒子内部宽度的小提琴。它使用以下作为 getComputedStyle 的垫片:

/**
 * getComputedStyle function for IE8
 * borrowed from:
 * http://missouristate.info/scripts/2013/common.js
 */
"getComputedStyle" in window || function() {
  function c(a, b, g, e) {
    var h = b[g];
    b = parseFloat(h);
    h = h.split(/\d/)[0];
    e = null !== e ? e : /%|em/.test(h) && a.parentElement ? c(a.parentElement, a.parentElement.currentStyle, "fontSize", null) : 16;
    a = "fontSize" == g ? e : /width/i.test(g) ? a.clientWidth : a.clientHeight;
    return "em" == h ? b * e : "in" == h ? 96 * b : "pt" == h ? 96 * b / 72 : "%" == h ? b / 100 * a : b;
  }
  function a(a, c) {
    var b = "border" == c ? "Width" : "", e = c + "Top" + b, h = c + "Right" + b, l = c + "Bottom" + b, b = c + "Left" + b;
    a[c] = (a[e] == a[h] == a[l] == a[b] ? [a[e]] : a[e] == a[l] && a[b] == a[h] ? [a[e], a[h]] : a[b] == a[h] ? [a[e], a[h], a[l]] : [a[e], a[h], a[l], a[b]]).join(" ");
  }
  function b(b) {
    var d, g = b.currentStyle, e = c(b, g, "fontSize", null);
    for (d in g) {
      /width|height|margin.|padding.|border.+W/.test(d) && "auto" !== this[d] ? this[d] = c(b, g, d, e) + "px" : "styleFloat" === d ? this["float"] = g[d] : this[d] = g[d];
    }
    a(this, "margin");
    a(this, "padding");
    a(this, "border");
    this.fontSize = e + "px";
    return this;
  }
  b.prototype = {};
  window.getComputedStyle = function(a) {
    return new b(a);
  };
}();

回答by Emile Bergeron

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 answerfails with a property like "backgroundColor"or "background-color"depending on the browser version because .getPropertyValueexpects the CSS property name and el.currentStyle[prop]needs the camel-case version.

Gabriel 的回答因类似"backgroundColor""background-color"取决于浏览器版本的属性而失败,因为.getPropertyValue需要 CSS 属性名称并el.currentStyle[prop]需要驼峰式版本。

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
}