javascript - 如何在 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");
如果您正在寻找列和行,那么:
td
如果您想要不同的颜色代码,请使用 csscolumns
tr
如果您想要不同的颜色代码,请使用 cssrows
<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");
});
推荐阅读
- android - Cannot resolve constructor TimePickerDialog
- c# - 十进制和双精度值解析为零
- oauth - 无法为三星 SmartThings 云到云集成实施 OAuth
- android - 深度链接使用 Launch Activity 而不是 Deep Linking Activity 不一致地打开应用程序
- swift - 导致错过布局的核心数据
- sql - 如何在 SQL 中使用伪列更新列值
- database - 我在 Laravel 中有一个 PDO 连接失败
- android - 如何检查 ROOM 数据库中的记录是否被删除?
- powershell - 退出 Powershell 的键盘快捷键
- html - CSS:过渡时间帮助,包含元素和动态(?)宽度的跨度填充