2012-03-02 72 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