在页面中显示一个隔行换色的html表格(JS)
时间: 2024-05-03 15:19:41 浏览: 13
以下是一个隔行换色的HTML表格的代码,使用JavaScript实现:
```html
<!DOCTYPE html>
<html>
<head>
<title>隔行换色的表格</title>
<style>
table, th, td {
border: 1px solid black;
border-collapse: collapse;
padding: 10px;
}
</style>
</head>
<body>
<table id="myTable">
<thead>
<tr>
<th>姓名</th>
<th>年龄</th>
<th>性别</th>
</tr>
</thead>
<tbody>
<tr>
<td>张三</td>
<td>20</td>
<td>男</td>
</tr>
<tr>
<td>李四</td>
<td>25</td>
<td>女</td>
</tr>
<tr>
<td>王五</td>
<td>30</td>
<td>男</td>
</tr>
<tr>
<td>赵六</td>
<td>35</td>
<td>女</td>
</tr>
</tbody>
</table>
<script>
var table = document.getElementById("myTable");
var rows = table.getElementsByTagName("tr");
for (var i = 0; i < rows.length; i++) {
if (i % 2 == 0) {
rows[i].style.backgroundColor = "#f2f2f2";
}
}
</script>
</body>
</html>
```
在这个例子中,我们使用了`if (i % 2 == 0)`语句进行行数的判断,如果是偶数行,就设置`background-color`属性为灰色。你可以修改这个颜色来适应你的需求。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)