//先把表格写出来
<body>
<table>
<thead>
<tr>
<th>书籍</th>
<th>价格</th>
<th>数量</th>
</tr>
</thead>
<tbody>
<tr>
<td>js</td>
<td>49.9</td>
<td>12</td>
</tr>
<tr>
<td>js</td>
<td>49.9</td>
<td>12</td>
</tr>
<tr>
<td>js</td>
<td>49.9</td>
<td>12</td>
</tr>
<tr>
<td>js</td>
<td>49.9</td>
<td>12</td>
</tr>
<tr>
<td>js</td>
<td>49.9</td>
<td>12</td>
</tr>
</tbody>
</table>
//接下来是css部分,这个写在head标签里此处为了方便阅读就写在这里面
<style>
table {
width: 800px;
margin: 100px auto;
text-align: center;
border-collapse: collapse;
font-size: 14px;
}
thead tr {
height: 30px;
background-color: skyblue;
}
tbody tr {
height: 30px;
}
tbody td {
border-bottom: 1px solid #d7d7d7;
font-size: 12px;
color: blue;
}
.bg {
background-color: red;
}
</style>
//接下来是js部分
<script>
//获取元素
var trs = document.querySelector('tbody').querySelectorAll('tr'); //获取tbody里的所有的tr
for(var i = 0; i < trs.length; i++) {//for循环遍历
trs[i].onmouseover = function() {//鼠标移入时的事件
this.className = 'bg';//this就是指鼠标移入的那一行就是当前此行,然后给他设置class="bg",上面的css样式
}
trs[i].onmouseout = function() {
this.className = '';//鼠标移出时什么都不设置把他的class设置为空就好
}
}
</script>
</body>
js表格隔行变色案例
最新推荐文章于 2024-04-07 20:24:55 发布
这篇博客介绍了一个简单的JavaScript实现,通过监听鼠标移入和移出事件,动态改变HTML表格中行的背景颜色。CSS部分用于设置表格的样式,包括宽度、对齐方式、边框等。JavaScript部分则获取表格中的行,并为每一行添加事件监听器,当鼠标悬停在某行上时,该行将变为红色,鼠标移出后恢复原状。这是一个基础的交互效果示例。
摘要由CSDN通过智能技术生成