[英]How can I set alternate color for both rows and columns using javascript in html?
I am creating a table by user inputs.我正在通过用户输入创建一个表。 User will input the height(number of rows) and width(number of columns) and it will create the table.
用户将输入高度(行数)和宽度(列数),它将创建表格。 Post creation of table I want to format the row and column in my table.
创建表后我想格式化表中的行和列。 I want to apply alternate colors for row and columns.
我想为行和列应用替代颜色。
Here is my code:这是我的代码:
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 |
Since you said you're using table
you can use something like this:既然你说你正在使用
table
你可以使用这样的东西:
$("tr:even").css("background-color", "#eeeeee");
$("tr:odd").css("background-color", "#ffffff");
if you're looking for columns and rows then:如果您正在寻找列和行,则:
use css for td
if you want different color code for columns
如果要为
columns
使用不同的颜色代码,请为td
使用 css
use css for tr
if you want different color code for rows
如果您想要不同的
rows
颜色代码,请使用 css for tr
<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 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");
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.