利用JS实现表格的隔行变色效果

我就是我 2023-07-03 03:18 2阅读 0赞

在开发中我们经常会看见表格隔行变色的案例
为了在看表格里面的数据不小心看错行数,所以就有了这样的效果
成果图在这里插入图片描述
html和css代码

  1. <style>
  2. table{
  3. width: 500px;
  4. margin: 100px auto;
  5. padding: 0;
  6. }
  7. thead{
  8. text-align: center;
  9. background-color:cornflowerblue;
  10. }
  11. td{
  12. border-bottom: 1px solid #ccc;
  13. }
  14. .bg{
  15. background-color: powderblue;
  16. }
  17. </style>
  18. ------html-----
  19. <table>
  20. <thead>
  21. <tr><td>这是表头</td></tr>
  22. </thead>
  23. <tbody>
  24. <tr><td>第1行</td></tr>
  25. <tr><td>第2行</td></tr>
  26. <tr><td>第3行</td></tr>
  27. <tr><td>第4行</td></tr>
  28. <tr><td>第5行</td></tr>
  29. </tbody>
  30. </table>
  31. <script>
  32. // 获取所有行
  33. var hang = document.querySelector("tbody").querySelectorAll("tr");
  34. //注册事件
  35. // 遍历每行,给每一行都绑定
  36. for(var i=0; i<hang.length; i++){
  37. // 鼠标经过事件
  38. hang[i].onmouseover = function(){
  39. this.className = "bg";
  40. }
  41. //鼠标离开事件
  42. hang[i].onmouseout = function(){
  43. this.className = "";
  44. }
  45. }
  46. </script>

这个案例在开发中经常会用到.希望大家喜欢.

发表评论

表情:
评论列表 (有 0 条评论,2人围观)

还没有评论,来说两句吧...

相关阅读