2009-11-17 81 views

回答

-1

DOM元素,怎麼我得到在CSS的 特定元素指定的所有 樣式?迭代所有css樣式名稱是否是 的情況?

是的。

還是有更優雅的方式?

我不知道更優雅(優雅是主觀上規模相當高),但肯定會是更短的和甜的,如果你利用一個庫如jQuery的,這裏有一個解決方案的人編碼爲回答另一個問題:

How Can I Get List Of All Element CSS Attributes with jQuery?

如何螢火蟲做呢?

我不知道。

-1

您可以通過所有的CSS樣式重複了這樣一個元素:

var myElement = document.getElementById('someId'); 
var myElementStyle = myElement.style; 

for(var i in myElementStyle){ 
    // if it's not a number-index, print it out. 
    if(/^[\d]+/.exec(i) == null){ 
     console.log("Style %s = %s", i, myElementStyle[i]); 
     /* 
     * Do other stuff here... 
     */ 
    } 
}
+1

嗨 - 感謝您的建議 - 但是myElementStyle [i]總是顯示爲空。我的樣式從外部css設置,而不是內聯 – 2009-11-17 14:09:50

+1

請確保您等待直到文檔加載後才運行此代碼。 – JasonWyatt 2009-11-17 14:45:15

+6

這僅適用於內聯樣式。 – syockit 2010-08-08 03:42:14

5

你應該能夠getComputedStyle得到它:

var css = window.getComputedStyle(element); 
for (var i=0; i<css.length; i++) { 
    console.log(css[i] +'='+css.getPropertyValue(""+css[i])) 
}