<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>表格</title>
<style>
.table-wrapper{
width: 500px;
margin: 0 auto;
}
table{
width: 500px;
height: 400px;
text-align: center;
}
.odd{
background-color: pink;
}
.even{
background-color: cornflowerblue;
}
.hight-light{
background-color: salmon;
}
</style>
</head>
<body>
<div class="table-wrapper">
</div>
<script>
//页面加载完毕后执行函数
window.onload=function(){
init();
handleSelect();
}
function init(){
let users=[
{
id:1,
name:'xl',
age:22
},
{
id:2,
name:'xw',
age:23
},
{
id:3,
name:'xb',
age:24
},
{
id:4,
name:'xl',
age:22
},
{
id:5,
name:'xw',
age:23
},
{
id:6,
name:'xb',
age:24
}
]
//使用js创建表格
let wrapper = document.querySelector('.table-wrapper')
let innerHTML='<table>';
innerHTML+='<thead>';
innerHTML+='<tr><th><input type="checkbox"></th><th>序号</th><th>姓名</th><th>年龄</th></tr>';
innerHTML+='</thead>';
innerHTML+='<tbody>';
for (let user of users) {
innerHTML+='<tr>'
innerHTML+='<td><input type="checkbox" value=""></td>';
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 = ' cornflowerblue';
// }
// }
//通过class设置样式
for (let index in rows) {
if(index%2==0){
// rows[index].className='odd'
rows[index].classList.add('odd')
}else{
rows[index].className=' even'
}
//鼠标在上面的时候添加样式
rows[index].onmouseover=function(){
this.classList.add('hight-light')
}
//离开的时候删除样式
rows[index].onmouseout=function(){
this.classList.remove('hight-light')
}
}
}
//实现复选框全选或全不选
function handleSelect(){
//添加事件监听
document.querySelector("thead [type='checkbox']").addEventListener('click',function(){
let list = document.querySelectorAll("tbody [type='checkbox']");
for (let ck of list) {
// ck.checked = !ck.checked;
ck.checked = this.checked;
}
})
}
</script>
</body>
</html>