隔行变色: <!DOCTYPE html> <html> <head> <meta charset="utf-8" /> <title></title> </head> <script> //给指定的表格添加n行 function addRows(n) { //1 获取table标签 var tb = document.getElementById("tb"); //2 使用for循环添加n行的html for(var i=0;i<n;i++) { //3 将其设置为 table标签的innerHTML tb.innerHTML+="<tr><td> </td></tr>"; } } function change() { //1 获得所有的tr标签数组 var trs=document.getElementsByTagName("tr"); //2 通过for循环,修改偶数元素的样式,实现偶数行的灰色 for(var i=0;i<trs.length;i++) { if((i+1)%2==0) { //背景色 trs[i].style.backgroundColor = "gray"; //鼠标形状 trs[i].style.cursor = "pointer"; trs[i].id = i; //使用标签的id属性存储行号 //绑定匿名函数 trs[i].onclick = function() { //通过读取id属性获得行号 alert("这是第"+(parseInt(this.id)+1)+"行"); } trs[i].onmouseover = function() { this.style.backgroundColor ="blue"; } trs[i].onmouseout = function() { if((parseInt(this.id)+1)%2==0) this.style.backgroundColor ="gray"; else this.style.backgroundColor ="white"; } } } } </script> <body > <center> <table id="tb" border="1" cellspacing="1" cellpadding="1"> </table> </center> </body> </html> ========================================================================================== 隔行变色通过伪类demo: <!DOCTYPE html> <html> <style> .even { background-color:gray; cursor:pointer; } .highlight { background-color:blue } </style> <head> <meta charset="utf-8" /> <title></title> </head> <script> //给指定的表格添加n行 function addRows(n) { //1 获取table标签 var tb = document.getElementById("tb"); //2 使用for循环添加n行的html for(var i=0;i<n;i++) { //3 将其设置为 table标签的innerHTML tb.innerHTML+="<tr><td> </td></tr>"; } } function change() { //1 获得所有的tr标签数组 var trs=document.getElementsByTagName("tr"); //2 通过for循环,修改偶数元素的样式,实现偶数行的灰色 for(var i=0;i<trs.length;i++) { if((i+1)%2==0) { //1 添加even的伪类 //trs[i].setAttribute("class","even"); trs[i].className = "even"; //绑定匿名函数 trs[i].onclick = function() { //通过读取id属性获得行号 alert("这是第"+(parseInt(this.id)+1)+"行"); } trs[i].onmouseover = function() { this.className += " highlight"; } trs[i].onmouseout = function() { var pos = this.className.indexOf(" highlight"); //去除叠加的伪类 this.className = this.className.substring(0,pos); } } } } </script> <body > <center> <table id="tb" border="1" cellspacing="1" cellpadding="1"> </table> </center> </body> </html> ==============================================================================================
时间: 2024-10-05 04:19:22