js实现的点击表格行实现背景变色代码:
如果表格内容较多的话,可能会造成错觉,由此可能会导致失误,为了防止这种失误的出现,一般会采用隔行变色或者点击(鼠标悬浮也是常用的)行实现变色效果,下面就通过代码实例介绍一下如何实现此效果。
代码如下:
<!DOCTYPE html><html><head><meta charset=" utf-8"><meta name="author" content="http://www.softwhy.com/" /><title>蚂蚁部落</title><script type="text/javascript"> window.onload=function(){ var item=document.getElementById("tb"); var tbody=item.getElementsByTagName("tbody")[0]; var trs=tbody.getElementsByTagName("tr"); var obj=null; var bgColor=null; for(var i=0;i<trs.length;i++){ if(i%2==0){ trs[i].style.backgroundColor="green"; } trs.onclick=function(){ if(obj!=null){obj.style.backgroundColor=bgColor;} bgColor=this.style.backgroundColor; obj=this; this.style.backgroundColor="red"; } } } </script></head><body><table id="tb" border="1"> <tbody> <tr> <td>蚂蚁部落一</td> <td>蚂蚁部落二</td> <td>蚂蚁部落三</td> </tr> <tr> <td>蚂蚁部落一</td> <td>蚂蚁部落二</td> <td>蚂蚁部落三</td> </tr> <tr> <td>蚂蚁部落一</td> <td>蚂蚁部落二</td> <td>蚂蚁部落三</td> </tr> <tr> <td>蚂蚁部落一</td> <td>蚂蚁部落二</td> <td>蚂蚁部落三</td> </tr> <tr> <td>蚂蚁部落一</td> <td>蚂蚁部落二</td> <td>蚂蚁部落三</td> </tr> <tr> <td>蚂蚁部落一</td> <td>第一行</td> <td>第一行</td> </tr> </tbody></table></body></html>
以上代码实现了我们想要的功能,表格不但实现了隔行变色的功能,而且当点击行的时候,能够实现当前行背景变色效果。下面介绍一下它的实现过程。
一.代码注释:
1.window.onload=function(){},文档内容完全加载完毕再去执行函数中的代码。
2.var item=document.getElementById("tb"),获取表格对象。
3. var tbody=item.getElementsByTagName("tbody")[0],获取tbody元素。
4.var trs=tbody.getElementsByTagName("tr"),获取表格行对象集合。
5.var obj=null,声明一个变量并赋值为null,用来存储表格行对象的引用。
6.var bgColor=null,声明一个变量并赋值为null,用来存储表格行对象的背景色。
7.for(var i=0;i<trs.length;i++){},通过for循环遍历每一个行对象。
8.if(i%2==0){trs.style.backgroundColor="green";} ,将奇数行的背景色设置为绿色。
9.trs.onclick=function(){},为每一个行注册onclick事件处理函数。
10.if(obj!=null){obj.style.backgroundColor=bgColor;},如果obj不等于null的时候,也就是不是第一次点击行的时候,将obj的背景颜色设置为bgColor。这里的目的就是将上一个点击行的背景颜色还原。
11.bgColor=this.style.backgroundColor,将当前行的背景色存储在bgColor。
12.obj=this,将当前行的索引存储于obj中。
13.this.style.backgroundColor="red",将当前行的背景颜色设置为红色。
二.相关阅读:
1.getElementsByTagName()函数可以参阅javascript的document.getElementsByTagName()一章节。
2.this可以参阅javascript的this用法详解一章节。
原文地址是:http://www.softwhy.com/forum.php?mod=viewthread&tid=11493
更多内容可以参阅:http://www.softwhy.com/javascript/
原标题:js实现的点击表格行实现背景变色代码
关键词:JS