js实现表格隔行换色
<!DOCTYPE html><html lang="en"><head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <style> .table-wrapper { width: 500px; margin: auto auto; } table{ width: 500px; height: 500px; text-align: center; } /* 奇数行 */ .odd{ background-color: pink; } /* 偶数行 */ .even{ background-color: royalblue; } .odd-high-light{ background-color: yellow; } .even-high-light{ background-color: white; } </style></head><body> <div class="table-wrapper"> </div> <script> // 页面加载完毕后执行函数 window.onload = function () { let users=[ { id:1, name:"Lynn", age:18 }, { id:2, name:"Lynn", age:18 }, { id:3, name:"Lynn", age:18 }, { id:4, name:"Lynn", age:18 } ] //使用js创建表格 let wrapper = document.querySelector('.table-wrapper'); let innerHTML = '<table>'; innerHTML += '<thead>'; innerHTML += '<tr><th>序号</th><th>姓名</th><th>年龄</th></tr>'; innerHTML += '</thead>'; innerHTML += '<tbody>'; for(let user of users){ innerHTML += '<tr>'; innerHTML += '<td>'+user.id+'</td>'; innerHTML += '<td>'+user.name+'</td>'; innerHTML += '<td>'+user.age+'</td>'; innerHTML += '</tr>'; } innerHTML += '</tbody>'; innerHTML += '</table>'; wrapper.innerHTML=innerHTML;//页面已经更新了 // 通过js设置行的背景色 let rows=wrapper.querySelectorAll('tbody tr'); //通过style设置样式 /* for(let index in rows){ if(index%2==0){ rows[index].style.backgroundColor='pink'; }else{ rows[index].style.backgroundColor='green'; } } */ //通过class设置样式 for(let index in rows){ if(index%2==0){ // className:有多个名字会覆盖样式 // classList:不会覆盖 rows[index].classList.add('odd'); rows[index].onmouseover=function(){ // console.log(this);//this表示当前行 this.classList.add('odd-high-light'); } rows[index].onmouseout=function(){ // console.log(this);//this表示当前行 this.classList.remove('odd-high-light'); } }else{ rows[index].className='even'; rows[index].onmouseover=function(){ // console.log(this);//this表示当前行 this.classList.add('even-high-light'); } rows[index].onmouseout=function(){ // console.log(this);//this表示当前行 this.classList.remove('even-high-light'); } } /* // 高亮,鼠标在上面添加高亮样式,鼠标移开删除高亮样式 rows[index].onmouseover=function(){ // console.log(this);//this表示当前行 this.classList.add('odd-high-light'); } rows[index].onmouseout=function(){ // console.log(this);//this表示当前行 this.classList.remove('odd-high-light'); } */ } } </script></body></html>