table
隔行变色是指在 HTML 表格中,通过 CSS 技术实现奇数行和偶数行显示不同的背景颜色,以增强表格的可读性和美观性。
:nth-child
来选择奇数行和偶数行。<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Table Row Highlighting</title>
<style>
table {
width: 100%;
border-collapse: collapse;
}
th, td {
padding: 8px;
text-align: left;
border-bottom: 1px solid #ddd;
}
tr:nth-child(even) {
background-color: #f2f2f2;
}
tr:nth-child(odd) {
background-color: #ffffff;
}
</style>
</head>
<body>
<table>
<tr>
<th>Name</th>
<th>Age</th>
</tr>
<tr>
<td>John Doe</td>
<td>30</td>
</tr>
<tr>
<td>Jane Smith</td>
<td>25</td>
</tr>
<tr>
<td>Mike Johnson</td>
<td>40</td>
</tr>
</table>
</body>
</html>
原因:
:nth-child
选择器使用错误。解决方法:
:nth-child
选择器是否正确使用,例如 tr:nth-child(even)
和 tr:nth-child(odd)
。!important
。<tr>
标签。<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Table Row Highlighting</title>
<style>
table {
width: 100%;
border-collapse: collapse;
}
th, td {
padding: 8px;
text-align: left;
border-bottom: 1px solid #ddd;
}
.even {
background-color: #f2f2f2;
}
.odd {
background-color: #ffffff;
}
</style>
</head>
<body>
<table id="myTable">
<tr>
<th>Name</th>
<th>Age</th>
</tr>
<tr>
<td>John Doe</td>
<td>30</td>
</tr>
<tr>
<td>Jane Smith</td>
<td>25</td>
</tr>
<tr>
<td>Mike Johnson</td>
<td>40</td>
</tr>
</table>
<script>
const table = document.getElementById('myTable');
const rows = table.getElementsByTagName('tr');
for (let i = 1; i < rows.length; i++) {
if (i % 2 === 0) {
rows[i].classList.add('even');
} else {
rows[i].classList.add('odd');
}
}
</script>
</body>
</html>
领取专属 10元无门槛券
手把手带您无忧上云