实现如下效果点击奇数行,改行背景色为蓝色,字体颜色成白色,偶数行背景色为红色,再次点击取消。总分里显示本行成绩总和。
时间: 2024-03-06 21:47:09 浏览: 130
可以使用以下代码实现:
HTML:
```html
<table id="myTable">
<thead>
<tr>
<th>姓名</th>
<th>语文</th>
<th>数学</th>
<th>英语</th>
<th>总分</th>
</tr>
</thead>
<tbody>
<tr>
<td>张三</td>
<td>90</td>
<td>80</td>
<td>70</td>
<td></td>
</tr>
<tr>
<td>李四</td>
<td>85</td>
<td>75</td>
<td>65</td>
<td></td>
</tr>
<tr>
<td>王五</td>
<td>95</td>
<td>85</td>
<td>75</td>
<td></td>
</tr>
</tbody>
</table>
```
CSS:
```css
table {
border-collapse: collapse;
width: 100%;
}
th, td {
border: 1px solid #ddd;
text-align: center;
padding: 8px;
}
th {
background-color: #f2f2f2;
}
tr:nth-child(odd) {
background-color: #f9a7b0;
color: #fff;
}
tr:nth-child(even) {
background-color: #a7c2f9;
color: #fff;
}
```
JavaScript:
```javascript
var table = document.getElementById("myTable");
var rows = table.getElementsByTagName("tr");
for (var i = 1; i < rows.length; i++) {
rows[i].onclick = function() {
var scoreCells = this.getElementsByTagName("td");
var totalScore = 0;
for (var j = 1; j < scoreCells.length - 1; j++) {
totalScore += parseInt(scoreCells[j].innerHTML);
}
if (this.style.backgroundColor === "" || this.style.backgroundColor === "rgb(255, 255, 255)") {
this.style.backgroundColor = "rgb(0, 0, 255)";
this.style.color = "#fff";
} else {
this.style.backgroundColor = "";
this.style.color = "";
}
scoreCells[scoreCells.length - 1].innerHTML = totalScore;
}
}
```
这段代码会为表格中的每一行添加点击事件,当点击某一行时,会计算该行除第一列和最后一列外的单元格中的总分,并将总分显示在该行的最后一列中。同时,如果该行为奇数行,则将背景色设置为蓝色,字体颜色设置为白色;如果该行为偶数行,则将背景色设置为红色,再次点击则取消背景色和字体颜色的设置。