首页 > 解决方案 > 如何在 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 |


标签: javascripthtmlcssstyles

解决方案


既然你说你正在使用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");
  });

小提琴


推荐阅读