下面是一个示例HTML代码,它创建了一个带有5行3列的表格,并为每一行添加了鼠标事件,当鼠标移到行上时,该行背景颜色变成蓝色,移出时恢复原来的颜色:
其中,onmouseover
和 onmouseout
事件分别表示鼠标移入和移出事件,changeColor()
函数根据传入的参数修改行的背景颜色。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>表格颜色变化</title>
<style>
table, th, td {
border: 1px solid black;
}
</style>
</head>
<body>
<table id="myTable">
<tr>
<th>姓名</th>
<th>年龄</th>
<th>性别</th>
</tr>
<tr onmouseover="changeColor(this, true)" onmouseout="changeColor(this, false)">
<td>张三</td>
<td>20</td>
<td>男</td>
</tr>
<tr onmouseover="changeColor(this, true)" onmouseout="changeColor(this, false)">
<td>李四</td>
<td>25</td>
<td>女</td>
</tr>
<tr onmouseover="changeColor(this, true)" onmouseout="changeColor(this, false)">
<td>王五</td>
<td>30</td>
<td>男</td>
</tr>
</table>
<script>
function changeColor(row, isMouseOver) {
if (isMouseOver) {
row.style.backgroundColor = "blue";
} else {
row.style.backgroundColor = "";
}
}
</script>
</body>
</html>
使用document.getelement改写上面的鼠标事件,解耦
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>表格颜色变化</title>
<style>
table, th, td {
border: 1px solid black;
}
</style>
</head>
<body>
<table id="myTable">
<tr>
<th>Name</th>
<th>Price</th>
<th>Stock</th>
</tr>
<tr>
<td>Product 1</td>
<td>$10</td>
<td>5</td>
</tr>
<tr>
<td>Product 2</td>
<td>$20</td>
<td>10</td>
</tr>
<tr>
<td>Product 3</td>
<td>$30</td>
<td>15</td>
</tr>
</table>
<script>
const table = document.getElementById("myTable");
const rows = table.getElementsByTagName("tr");
for (let i = 1; i < rows.length; i++) {
rows[i].addEventListener("mouseover", function() {
this.style.backgroundColor = "blue";
});
rows[i].addEventListener("mouseout", function() {
this.style.backgroundColor = "";
});
}
</script>
</body>
</html>
这里我们首先使用 document.getElementById
方法获取表格元素,并获取表格中的所有行。然后使用 addEventListener
方法为每一行添加 mouseover
和 mouseout
事件监听器,当鼠标移入时设置背景色为蓝色,当鼠标移出时恢复原来的颜色。注意在事件处理函数中使用 this
表示当前行的元素。
继续解耦,如果有不同区域的行,可以为表格行添加一个类名,用于选择器。
<table id="myTable">
<thead>
<tr>
<th>Name</th>
<th>Price</th>
<th>Stock</th>
<th>Note</th>
</tr>
</thead>
<tbody>
<tr class="table-row">
<td>Product 1</td>
<td>$10.00</td>
<td>20</td>
<td>Note 1</td>
</tr>
<tr class="table-row">
<td>Product 2</td>
<td>$15.00</td>
<td>10</td>
<td>Note 2</td>
</tr>
<tr class="table-row">
<td>Product 3</td>
<td>$20.00</td>
<td>5</td>
<td>Note 3</td>
</tr>
</tbody>
</table>
此时的JS代码为:
const table = document.getElementById('myTable');
table.addEventListener('mouseover', function(event) {
// 如果鼠标移入的是表格行,则设置其背景颜色为蓝色
if (event.target.classList.contains('table-row')) {
event.target.style.backgroundColor = 'blue';
}
});
table.addEventListener('mouseout', function(event) {
// 如果鼠标移出的是表格行,则将其背景颜色恢复
if (event.target.classList.contains('table-row')) {
event.target.style.backgroundColor = '';
}
});
这样,当鼠标移入或移出表格行时,其背景颜色就会相应地变化。由于事件是委托到表格上的,因此不需要为每一行都绑定事件处理器,从而提高了代码的可维护性。