4.JavaScript实现表格隔行变色

﹏ヽ暗。殇╰゛Y 2022-12-12 04:38 225阅读 0赞

css代码如下:

  1. <style> *{
  2. margin: 0;
  3. padding: 0;
  4. }
  5. table{
  6. width: 80%;
  7. text-align: center;
  8. margin: 50px auto;
  9. border: 1px solid black;
  10. border-collapse: collapse;
  11. /* 合并边框 没有空隙 */
  12. }
  13. th,td{
  14. order: 1px solid black;
  15. padding: 15px;
  16. }
  17. td{
  18. font-size: 18px;
  19. }
  20. .odd{
  21. background-color: rgb(253, 197, 206);
  22. }
  23. .even{
  24. background-color: rgb(172, 250, 152);
  25. }
  26. </style>~

html代码如下

  1. <table>
  2. <thead>
  3. <tr>
  4. <th>编号</th>
  5. <th>姓名</th>
  6. <th>出生日期</th>
  7. </tr>
  8. </thead>
  9. <tbody>
  10. <tr>
  11. <td>01</td>
  12. <td></td>
  13. <td>2001.06.10</td>
  14. </tr>
  15. <tr>
  16. <td>02</td>
  17. <td></td>
  18. <td>2001.06.10</td>
  19. </tr>~
  20. </tbody>
  21. </table>~

js代码如下:

  1. <script>
  2. var trs = document.querySelectorAll('tbody tr') console.log(trs)
  3. for(var i=0;i<trs.length;i++){
  4. if(i%2==0){
  5. trs[i].className='odd'
  6. }else{
  7. trs[i].className='even'
  8. }
  9. // 为tr注册 onmouseover事件(鼠标进入)
  10. trs[i].onmouseover=function(){
  11. this.style.backgroundColor='#eee'
  12. }
  13. // 为 tr 注册 onmouseout 事件(鼠标离开)
  14. trs[i].onmouseout=function(){
  15. this.style.backgroundColor=''
  16. }
  17. }
  18. </script>~

发表评论

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

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

相关阅读