イナヅマTVログ

[JavaScript] Memo, getComputedStyleでCSS

| 0件のコメント

getComputedStyle

要素の算出スタイルを返します。

MDN(ja): window.getComputedStyle
MDN(en): Window.getComputedStyle()

caniuse.com: getComputedStyle
IE は 9 から。
Safari は 5.1 から。

iOS Safari は 6 から。
Android は 4 から。
2.3 は Partial support になってる。

var element, style, margin;
element = document.getElementById( "element-id" ),
style = window.getComputedStyle( element, null ),
margin = style.getPropertyValue( "margin" );

var style = window.getComputedStyle(element[, pseudoElt]);
pseudoEltはnullで良いらしい。

style は、CSSStyleDeclaration オブジェクトです。

W3C: CSSStyleDeclaration

read-only and contains only absolute values

getPropertyValue の他に getPropertyCSSValue も…

互換コード

非サポートブラウザのためのコードが公開されてた。
stackoverflow: getComputedStyle like javascript function for IE8

if (!window.getComputedStyle) {
    window.getComputedStyle = function(el, pseudo) {
        this.el = el;
        this.getPropertyValue = function(prop) {
            var re = /(\-([a-z]){1})/g;
            if (prop == 'float') prop = 'styleFloat';
            if (re.test(prop)) {
                prop = prop.replace(re, function () {
                    return arguments[2].toUpperCase();
                });
            }
            return el.currentStyle[prop] ? el.currentStyle[prop] : null;
        }
        return this;
    }
}

オリジナルはこちらだそうです。
SNIPPLR: getComputedStyle for IE
コメントで「正しい値を返さないー」て言ってる人いるなぁ。

コメントを残す

必須欄は * がついています


このサイトはスパムを低減するために Akismet を使っています。コメントデータの処理方法の詳細はこちらをご覧ください