如何使用html中的javascript为行和列设置备用颜色



我正在通过用户输入创建一个表。用户将输入高度(行数(和宽度(列数(,然后创建表格。创建表后,我想格式化表中的行和列。我想为行和列应用交替的颜色

这是我的代码:

function createGrid()
{
var num_rows = document.getElementById('row').value;
var num_cols = document.getElementById('col').value;
var theader = 
'<table id="tblMain" border="1" >n';
var tbody = '';
for( var i=0; i<num_rows;i++)
{
tbody += '<tr>';
for( var j=0; j<num_cols;j++)
{
tbody += '<td>';
tbody += 'Cell ' + i + ',' + j;
tbody += '</td>';
}
tbody += '</tr>n';
}
var tfooter = '</table>';
document.getElementById('wrapper').innerHTML = theader + tbody + tfooter;
}
</script>
<style>
td{
background: yellow;
}
tr td:nth-child(even) {
background-color: red;
}
} 
</style>
<body>
<form name="tablegen">
<label>Width: <input type="text" name="col" id="col"/></label><br/>
<label>Height: <input type="text" name="row" id="row"/></label><br />
<input name="generate" type="button" value="Create Table!" onclick='createGrid();'/>
</form>
<div id="wrapper"></div>```

**I want my table in the folowing format(Red and green are the colors for the rows and columns):**
|Red    |   Green  |    Red     |   Green |
|Green  |   Red    |   Green    |   Red   |
|Red    |   Green  |    Red     |   Green |

既然你说你在使用table,你就可以使用这样的东西:

$("tr:even").css("background-color", "#eeeeee");
$("tr:odd").css("background-color", "#ffffff");

如果您正在查找,则:

如果您想为columns使用不同的颜色代码,请为td使用css

如果您想为rows使用不同的颜色代码,请为tr使用css

<table id="id2" border="1">
<tr>
<td>row 1, cell 1</td>
<td>row 1, cell 2</td>
</tr>
<tr>
<td>row 2, cell 1</td>
<td>row 2, cell 2</td>
</tr>
<tr>
<td>row 1, cell 1</td>
<td>row 1, cell 2</td>
</tr>
<tr>
<td>row 2, cell 1</td>
<td>row 2, cell 2</td>
</tr>

CSS

$(document).ready(function () {
$("table#id2 td:even").css("background-color", "LightGray");
$("table#id2 tr:even").css("background-color", "LightBlue");
$("table#id2 tr:odd td").css("background-color", "LightYellow");
});

Fiddle

最新更新