DOM:表格隔行变色
表格隔行变色
实例代码:
<!DOCTYPE html> <html> <head> <meta http-equiv="Content-Type" content="text/html;charset=UTF-8"> <title></title> <style> table{ border: 1px red solid; } tr{ width: 100%; height: 40px; } td{ width: 100px; border: 1px darkred solid; } </style> </head> <body> <table id="tb" cellspacing = '0'> <tr class='tr1'> <td>1</td> <td>1</td> </tr> <tr class='tr1'> <td>2</td> <td>2</td> </tr> <tr class='tr1'> <td>3</td> <td>3</td> </tr> <tr class='tr1'> <td>4</td> <td>4</td> </tr> </table> <script> var tr = document.querySelectorAll('.tr1'); var td = document.querySelectorAll('td'); var table= document.querySelectorAll('#tb') for (let i = 0; i < tr.length; i++) { tr[i] = document.querySelector('.tr1'); if (i % 2 == 0) { tr[i].style.backgroundColor = 'green'; } else { tr[i].style.backgroundColor = 'red'; } } </script> </body> </html>
效果图: