JS实现table表格在鼠标移动出现一行变色或者十字叉变色

时间:2021-03-17 09:38:07

1,一行变色

<script>
function trBg(){
var tab=document.getElementById("table");
var tr=tab.getElementsByTagName("tr");
for(var i=;i<tr.length;i++){
if(i%==){
tr[i].style.backgroundColor="#fff"; tr[i].onmouseover=function(){
this.style.background="red";
};
tr[i].onmouseout=function(){
this.style.background="#fff";
}
}else{
tr[i].style.backgroundColor="#fff"; tr[i].onmouseover=function(){
this.style.background="blue";
};
tr[i].onmouseout=function(){
this.style.background="#fff";
}
}
}
}
window.onload=trBg;
</script>
<table id="table" border="" width="" cellspacing="" cellpadding="">
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
<tr>
<td></td>
<td></td>
<td></td>
<td></td>
<td></td>
</tr>
</table>

JS实现table表格在鼠标移动出现一行变色或者十字叉变色

2,十字叉变色

<table id="table" border="" width="" cellspacing="" cellpadding=""></table>

<script>

    var html = '';
for(var i = ; i < ; i++){
html += '<tr>'
for(var j = ; j < ; j++){
html += '<td data-index="'+ i + '-' + j +'">' + i + '-'+ j + '</td>'
}
html += '</tr>'
}
document.getElementById("table").innerHTML = html; var table = document.getElementById("table");
if(table.rows.length > ){
var rows = table.rows;
for(var i=; i<rows.length; i++){
(function(i){
var tds=rows[i];
for(var j=; j<tds.cells.length; j++){
var obj=tds.cells[j];
obj.onmouseover=function(e){
var val = this.getAttribute('data-index');
var x = val.split('-')[];
var y = val.split('-')[];
console.log(val) var tds = document.getElementsByTagName("td");
for(var k=; k<tds.length; k++){
tds[k].style.backgroundColor="#fff";
} table.rows[i].style.backgroundColor="red"; for(var k=; k<rows[i].cells.length; k++){
table.rows[x].cells[k].style.backgroundColor="red";
}
for(var k=; k<rows.length; k++){
table.rows[k].cells[y].style.backgroundColor="red";
} };
}
})(i)
} }
</script>

JS实现table表格在鼠标移动出现一行变色或者十字叉变色