1,一行變色html
<script> function trBg(){ var tab=document.getElementById("table"); var tr=tab.getElementsByTagName("tr"); for(var i=0;i<tr.length;i++){ if(i%2==0){ 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="1" width="400" cellspacing="0" cellpadding="0"> <tr> <td>11111</td> <td>22222</td> <td>33333</td> <td>44444</td> <td>55555</td> </tr> <tr> <td>11111</td> <td>22222</td> <td>33333</td> <td>44444</td> <td>55555</td> </tr> <tr> <td>11111</td> <td>22222</td> <td>33333</td> <td>44444</td> <td>55555</td> </tr> <tr> <td>11111</td> <td>22222</td> <td>33333</td> <td>44444</td> <td>55555</td> </tr> <tr> <td>11111</td> <td>22222</td> <td>33333</td> <td>44444</td> <td>55555</td> </tr> <tr> <td>11111</td> <td>22222</td> <td>33333</td> <td>44444</td> <td>55555</td> </tr> <tr> <td>11111</td> <td>22222</td> <td>33333</td> <td>44444</td> <td>55555</td> </tr> <tr> <td>11111</td> <td>22222</td> <td>33333</td> <td>44444</td> <td>55555</td> </tr> </table>
2,十字叉變色this
<table id="table" border="1" width="600" cellspacing="0" cellpadding="0"></table> <script> var html = ''; for(var i = 0; i < 10; i++){ html += '<tr>' for(var j = 0; j < 10; 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 > 0){ var rows = table.rows; for(var i=0; i<rows.length; i++){ (function(i){ var tds=rows[i]; for(var j=0; j<tds.cells.length; j++){ var obj=tds.cells[j]; obj.onmouseover=function(e){ var val = this.getAttribute('data-index'); var x = val.split('-')[0]; var y = val.split('-')[1]; console.log(val) var tds = document.getElementsByTagName("td"); for(var k=0; k<tds.length; k++){ tds[k].style.backgroundColor="#fff"; } table.rows[i].style.backgroundColor="red"; for(var k=0; k<rows[i].cells.length; k++){ table.rows[x].cells[k].style.backgroundColor="red"; } for(var k=0; k<rows.length; k++){ table.rows[k].cells[y].style.backgroundColor="red"; } }; } })(i) } } </script>