效果图:
第一个表格点击后一列的表格会变色
第二个表格隔行变色
第三个表格点击后一行的表格会变色
三个表格的基本样式:
css部分
<style>
table{
border: 1px red solid;
}
tr{
width: 100%;
height: 40px;
}
td{
width: 100px;
border: 1px darkred solid;
}
</style>
html部分
<table id="tb" cellspacing="0">
<tr>
<td>hello</td>
<td>hello</td>
<td>hello</td>
<td>hello</td>
<td>hello</td>
<td>hello</td>
<td>hello</td>
<td>hello</td>
<td>hello</td>
<td>hello</td>
</tr>
<tr>
<td>hello</td>
<td>hello</td>
<td>hello</td>
<td>hello</td>
<td>hello</td>
<td>hello</td>
<td>hello</td>
<td>hello</td>
<td>hello</td>
<td>hello</td>
</tr>
<tr>
<td>hello</td>
<td>hello</td>
<td>hello</td>
<td>hello</td>
<td>hello</td>
<td>hello</td>
<td>hello</td>
<td>hello</td>
<td>hello</td>
<td>hello</td>
</tr>
<tr>
<td>hello</td>
<td>hello</td>
<td>hello</td>
<td>hello</td>
<td>hello</td>
<td>hello</td>
<td>hello</td>
<td>hello</td>
<td>hello</td>
<td>hello</td>
</tr>
</table>
1.点击横排变色
1.把所有的td的背景颜色设置为白色
2.获取当前点击的元素是一横排中的第x个元素
3.把每一横排的第x个元素 设置为red
先获取到每一个需要用到的节点
var tb=document.querySelector("#tb")
var trs=document.querySelectorAll("tr")
var tds=document.querySelectorAll("td")
设计点击事件
tds[i].onclick=function(){}
先把所有的td的背景颜色设置为白色
tds.forEach((el)=>{
el.style.backgroundColor="white"
})
设计一段函数以获取x
Object.prototype.indexof1=function(){
var arr=this.parentElement.children
for(let i=0;i<arr.length;i++){
if(arr[i]===this){
return i
}
}
}
使用let x=tds[i].indexof1()可以获得x
第x个元素 设置为red
trs.forEach((el)=>{
//el是tr元素
el.children[x].style.backgroundColor="red"
})
又因为是每个横排都要执行一遍
加个for循环
for(let i=0;i<tds.length;i++){
tds[i].onclick=function(){
// console.log(this,tds[i])
//1.把所有的td的背景颜色设置为白色
//2.获取当前点击的元素是一横排中的第x个元素
//3.把每一横排的第x个元素 设置为red
//排它思想
tds.forEach((el)=>{
// console.log(el,11)
el.style.backgroundColor="white"
})
let x=tds[i].indexof1()
trs.forEach((el)=>{
//el是tr元素
el.children[x].style.backgroundColor="red"
})
}
}
2.静态隔行变色
1.获取tr元素的集合trs
var trs=document.querySelectorAll("#tb2 tr")
2.用for循环将元素遍历处理来用if判断奇偶数
if(i%2){
}
3.修改元素的值
trs[i].style.backgroundColor="gray"
3.点击纵列变色
1.把所有的tr的背景颜色设置为白色
el.style.backgroundColor="white"
2.检测点击事件tr的集合第i个元素被点击然后设置为灰色
trs[i].onclick=function(){
trs[i].style.backgroundColor="gray"
}
3.每一行都重复一次
(()=>{var trs=document.querySelectorAll("#tb3 tr")
for(let i=0;i<trs.length;i++){
trs[i].onclick=function(){
trs.forEach((el)=>{
el.style.backgroundColor="white"
})
// console.log(i,trs[i],11111)
trs[i].style.backgroundColor="gray"
}
}
})()