Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
209 views
in Technique[技术] by (71.8m points)

javascript - getComputedStyle (or) $.css(map) <-- to get every style declaration

Aside from looping through an array that has each style property declared, is there any way to get a key/value output of all styling of a dom element?

My fallback is iterating through the keys listed on: http://www.w3.org/TR/DOM-Level-2-Style/css.html#CSS-CSSview-getComputedStyle

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

is there any way to get a key/value output of all styling of a dom element?

Yes, but don't expect the exact handling of values (units etc.) to be the same cross-browser.

var styles= [];

// The DOM Level 2 CSS way
//
if ('getComputedStyle' in window) {
    var cs= getComputedStyle(element, '');
    if (cs.length!==0)
        for (var i= 0; i<cs.length; i++)
            styles.push([cs.item(i), cs.getPropertyValue(cs.item(i))]);

    // Opera workaround. Opera doesn't support `item`/`length`
    // on CSSStyleDeclaration.
    //
    else
        for (var k in cs)
            if (cs.hasOwnProperty(k))
                styles.push([k, cs[k]]);

// The IE way
//
} else if ('currentStyle' in element) {
    var cs= element.currentStyle;
    for (var k in cs)
        styles.push([k, cs[k]]);
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...