2013-08-06 40 views
3

在大多數瀏覽器(例如Firefox,Opera)上獲取元素的計算後的樣式會返回一個類型爲CSSStyleDeclaration的漂亮對象。在Chrome 28和PhantomJS 1.9上,我得到一個以編號鍵開頭的對象,其中列出了所有CSS屬性,然後是屬性(對於Chrome)。WebKit/Phantomjs爲什麼getComputedStyles的輸出是這種方式?

例如,在歌劇: enter image description here

在Chrome中28: enter image description here

,然後最終你得到有用的部分: enter image description here

在PhantomJS 1.9

它甚至更糟的是,你獲取編號屬性,然後只有兩個命名屬性:lenght和cssText。

... 
219: 'glyph-orientation-horizontal', 
220: 'glyph-orientation-vertical', 
221: '-webkit-svg-shadow', 
222: 'vector-effect', 
length: 223, 
cssText: 'background-attachment: scroll; background-clip: border-box; background-color: rgba(0, 0, 0, 0); background-image: none; background-o... 

回答

0

getComputedStyle在Chrome枚舉屬性名稱。某些CSS屬性具有別名,因此通過同一結構中的數組或哈希訪問別名可以提供兩全其美的優點。

使用JSON.parseJSON.stringify跨瀏覽器的標準化值:

var foo = getComputedStyle(document.body); 
 
    
 
    console.log(JSON.parse(JSON.stringify(foo), function(key, value){ if (/[0-9]+/.test(key)) return undefined; else return value; }))

參考

1

返回的對象在所有情況下應該是CSSStyleDeclaration實例(https://developer.mozilla.org/en-US/docs/Web/API/CSSStyleDeclaration)。

該目的只應該有數量索引值和一個length(使它陣列狀)和cssText

Chrome實現添加了非標準命名屬性。如果您想要屬性/值對的簡單對象,則可以在實例上使用getPropertyValue方法。例如(並且該代碼的大部分來自MDN上的示例)

function simpleStyles(node) { 
    var style = window.getComputedStyle(node); 
    var styleMap = {}; 
    for (var i = 0; i < style.length; i++) { 
    var prop = style[i]; //the numbered props 
    var value = style.getPropertyValue(prop); //access the value; 
    styleMap[prop] = value; 
    } 
    return styleMap; 
} 

//or fancier 

function simpleStyles(node) { 
    return Array.prototype.reduce.call(window.getComputedStyle(node), function(map, prop, _, style) { 
    map[prop] = style.getPropertyValue(prop); 
    return map; 
    }, {}); 
}