2012-03-02 69 views
-1

我有一個HTML表,其中每行有一些樣式類分配(動態通過服務器端代碼)。如何獲取分配給html表的CSS屬性?

的HTML看起來像:

<tr id= "2977" class ="x y z a b c" > 

我使用這個訪問行的背景顏色:

document.getElementById("2977").style.backgroundColor 

但我無法讀取任何風格的屬性;上述行返回null。如果我在Chrome中檢查行元素,它將顯示該行的十六進制顏色。

如何讀取元素的當前背景顏色?

+0

你應該發佈更多的html。由於您發佈的js是有效的。桌子裏有tr嗎? – 2012-03-02 12:22:38

回答

1

http://jsfiddle.net/UvYxc/工作

HTML

<table> 
    <tr style="background:red;" id= "2977" class ="x y z a b c" > 
     <td>RED</td> 
    </tr> 
</table> 

JS

document.getElementById("2977").style.backgroundColor="blue" 
alert(document.getElementById("2977").style.backgroundColor);​ 

或者

document.getElementById("2977").className += " blue"; 
document.getElementById("2977").className += " red"; 

function getStyle(el, cssprop){ 
    //IE 
    if (el.currentStyle) 
     return el.currentStyle[cssprop] 
    //Firefox 
    else if (document.defaultView && document.defaultView.getComputedStyle) 
     return document.defaultView.getComputedStyle(el, "")[cssprop] 
    else //try and get inline style 
     return el.style[cssprop] 
} 

var el = document.getElementById("2977"); 
alert(getStyle(el, "backgroundColor")); 
alert(getStyle(el, "color")); 

here

+0

這正是我正在做的。唯一不同的是顏色由外部樣式表文件設置(而不是手動分配)。我正在通過你寫的第二行閱讀它。 – 2012-03-02 12:22:14

+0

試試這個小提琴,這是你的意思嗎? http://jsfiddle.net/UvYxc/1/ – 2012-03-02 12:26:21

+0

是的。但在我的情況下,我沒有固定的顏色分配。一些樣式表類正在分配一種顏色。並且我不知道該樣式表的工作方式 – 2012-03-02 12:30:20

2

您是否可以通過以下方式閱讀樣式屬性?

document.getElementById("2977").getAttribute("style"); 

另外,如果你能使用jQuery嘗試

$('#2977').css('background-color'); 
+0

getAttribute(「style」)給出null – 2012-03-02 12:19:45

1

的代碼實際上看起來適合我。也許有更多的細節,我可以幫助你更好。

+0

請問你能告訴你需要什麼細節? – 2012-03-02 12:18:24

+0

您聲明表格的HTML代碼。這更有可能是你在JavaScript代碼中出現錯誤。 – user1242756 2012-03-02 12:31:10

1

你執行JavaScript的頁面加載後小提琴。

試試這個作爲測試:

function init() { 
    document.getElementById("2977").style.backgroundColor = "black"; 
    alert(document.getElementById("2977").style.backgroundColor); 
} 
window.onload = init; 
4

如果你正在尋找不使用任何JavaScript庫,你可以做這樣的事情:

row = document.getElementById("2977") 
var bgStyle = window.getComputedStyle(row).getPropertyValue("background-color"); 

我趕緊看了這個,我我不確定是否有任何陷阱。

+0

thnx @dmbania,它的工作。 – 2012-03-02 12:33:54

+0

它爲每一行提供相同的rgb顏色。但是對於每一行我都有不同的背景顏色 – 2012-03-02 12:42:22

+0

你如何循環你的TR?你如何檢查你從getComputedStyle中收到的價值? – dmbania 2012-03-02 13:29:57