使用 javascript 设置表行的样式属性

Setting the style property for table rows using javascript

本文关键字:样式 属性 javascript 设置 使用      更新时间:2023-09-26

>假设我有一个这样的页面

<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]并更改背景。但是有没有其他有效的方法呢?

您可以遍历元素并更改背景

var els = document.getElementById("t1").getElementsByTagName("td");
for(var i=0;i<els.length;i++){
  els[i].style.background = "green"   
}

在行上放置一个类,并将背景放在 CSS 中,就像处理表格一样

你可以试试这个:

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;

我使用JQuery。

$('td').css('background','#3232');