使用 javascript 设置表格行的样式属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/11889349/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Setting the style property for table rows using javascript
提问by Jeff
Assume I have a page like this
假设我有一个这样的页面
<html>
<body>
<table id="t1">
<tr><th>Head1</th><th>Head2</th></tr>
<tr><td>1</td><td>2</td></tr>
<tr><td>3</td><td>4</td></tr>
</table>
</body>
</html>
My CSS
我的 CSS
table th { background:color1;}
table td { background:color2;}
How do I change the background color for all rows except header row with a javascript statement. Is looping through each row and column the only method?
如何使用 javascript 语句更改除标题行以外的所有行的背景颜色。遍历每一行和每一列是唯一的方法吗?
I can get document.getElementById('t1').rows[1]
and rows[2]
and change background. But is there another efficient way?
我可以document.getElementById('t1').rows[1]
和rows[2]
和变化的背景。但是还有另一种有效的方法吗?
回答by Clyde Lobo
You can loop over the elements and change the background
您可以遍历元素并更改背景
var els = document.getElementById("t1").getElementsByTagName("td");
for(var i=0;i<els.length;i++){
els[i].style.background = "green"
}
回答by Teemu
You can try this:
你可以试试这个:
table th {background: color1;}
table tbody {background: color2;}
<table id="t1">
<tr><th>Head1</th><th>Head2</th></tr>
<tbody id="t2">
<tr><td>1</td><td>2</td></tr>
<tr><td>3</td><td>4</td></tr>
</tbody>
</table>
And in the script:
在脚本中:
document.getElementById('t2').style.backgroundColor=color3;
EDIT
编辑
It's also possible to add a rule to the particular styleSheet
.
也可以向特定的styleSheet
.
CSS:
CSS:
table th {background: color1;}
table td {background: color2;}
Script:
脚本:
var sSheet = document.styleSheets[0];
if (sSheet.insertRule) {
sSheet.insertRule('td {background-color: color3}', sSheet.cssRules.length);
} else { // For IE < 9
sSheet.addRule('td', 'background-color: color3', -1);
}
You can also modify an existing rule itself:
您还可以修改现有规则本身:
var tdRule,
sSheet = document.styleSheets[0];
if (sSheet.cssRules) {
tdRule = sSheet.cssRules[1];
} else { // For IE < 9
tdRule = sSheet.rules[1];
}
tdRule.style.backgroundColor = color3;
回答by Santiago Elvira Ramirez
put a class on the rows and put backgrounds in css like you do with the tables
在行上放置一个类并将背景放在 css 中,就像您对表格所做的一样
回答by Francisco Albert
I use JQuery.
我使用 JQuery。
$('td').css('background','#3232');