利用JS实现表格的隔行变色效果
在开发中我们经常会看见表格隔行变色的案例
为了在看表格里面的数据不小心看错行数,所以就有了这样的效果
成果图
html和css代码
<style>
table{
width: 500px;
margin: 100px auto;
padding: 0;
}
thead{
text-align: center;
background-color:cornflowerblue;
}
td{
border-bottom: 1px solid #ccc;
}
.bg{
background-color: powderblue;
}
</style>
------html-----
<table>
<thead>
<tr><td>这是表头</td></tr>
</thead>
<tbody>
<tr><td>第1行</td></tr>
<tr><td>第2行</td></tr>
<tr><td>第3行</td></tr>
<tr><td>第4行</td></tr>
<tr><td>第5行</td></tr>
</tbody>
</table>
<script>
// 获取所有行
var hang = document.querySelector("tbody").querySelectorAll("tr");
//注册事件
// 遍历每行,给每一行都绑定
for(var i=0; i<hang.length; i++){
// 鼠标经过事件
hang[i].onmouseover = function(){
this.className = "bg";
}
//鼠标离开事件
hang[i].onmouseout = function(){
this.className = "";
}
}
</script>
这个案例在开发中经常会用到.希望大家喜欢.
还没有评论,来说两句吧...