LCJ*_*LCJ 3 html javascript css jquery
我有以下HTML表格.我需要为每列提供背景颜色(第一列=红色,第二列=黄色,第三列=蓝色).我怎么能用CSS做到这一点?
注意:这需要在IE6以后工作.
http://jsfiddle.net/Lijo/kw4yU/
<table id = "myTable">
<thead>
<tr>
<th>
Name
</th>
<th>
Address
</th>
<th>
Age
</th>
</tr>
</thead>
<tr>
<td>
Lijo
</td>
<td>
India
</td>
<td>
27
</td>
</tr>
</table>
Run Code Online (Sandbox Code Playgroud)
编辑:
我通过将js代码放在document.ready中来实现它.感谢@Jose Rui Santos http://jsfiddle.net/Lijo/kw4yU/11/
另一个解决方案是http://jsfiddle.net/Lijo/kw4yU/12/
另一种方法:列宽设置 - HTML表
使用+选择器
?#myTable tr td { /* makes all columns red */
background-color: red;
}
#myTable tr td + td { /* makes 2nd and 3rd columns yellow */
background-color: yellow;
}
#myTable tr td + td + td { /* makes 3rd column blue */
background-color: blue;
}
Run Code Online (Sandbox Code Playgroud)
编辑
上述CSS仅更改数据单元格的背景颜色.如果您还想包含表头,请执行以下操作:
#myTable tr th,
#myTable tr td {
background-color: red;
}
#myTable tr th + th,
#myTable tr td + td {
background-color: yellow;
}
#myTable tr th + th + th,
#myTable tr td + td + td {
background-color: blue;
}
Run Code Online (Sandbox Code Playgroud)
EDIT2
一个javascript解决方案是使用jQuery
$("#myTable th, #myTable td").each(function (i) {
$(this).css('background-color', ['red', 'yellow', 'blue'][i % 3]);
});
Run Code Online (Sandbox Code Playgroud)
你可以这样做:
td:nth-child(1){
background-color: #f00;
}
td:nth-child(2){
background-color: #ff0;
}
td:nth-child(3){
background-color: #00f;
}
Run Code Online (Sandbox Code Playgroud)
但是,这是使用CSS3,因此如果您想支持旧版浏览器,则需要使用JavaScript.