假设我有一个这样的页面
<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>
我的CSS
table th { background:color1;}
table td { background:color2;}
如何使用javascript语句更改除标题行之外的所有行的背景颜色。循环遍历每一行和列是唯一的方法吗?
我可以获得document.getElementById('t1').rows[1]
和rows[2]
并更改背景。但还有另一种有效的方法吗?
答案 0 :(得分:4)
您可以遍历元素并更改背景
var els = document.getElementById("t1").getElementsByTagName("td");
for(var i=0;i<els.length;i++){
els[i].style.background = "green"
}
答案 1 :(得分:3)
在行上放置一个类,并将背景放在css中,就像使用表格
一样答案 2 :(得分:2)
你可以试试这个:
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>
在剧本中:
document.getElementById('t2').style.backgroundColor=color3;
修改强>
还可以向特定styleSheet
添加规则。
CSS:
table th {background: color1;}
table td {background: color2;}
脚本:
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);
}
您还可以修改现有规则:
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;
答案 3 :(得分:0)
我使用JQuery。
$('td').css('background','#3232');