前言:这个系列主要是对之前学习JavaScript实现的一些小demo的总结,总觉得不能这样学过了就算了,趁着假期就好好总结一下吧。
在平常的网站开发中,我们常常会遇到这样的一个需求,就是需要实现表格高亮显示,所谓的高亮显示又是怎么一回事呢?其实就是当我们的鼠标移进表格的某一行,某一行就会改变原来的背景颜色,而当我们把鼠标移出的时候,表格的某一行又会恢复到原来的背景颜色,那么这种效果是怎么实现的呢?
所用到的技术点如下:
JS事件:
onload:页面加载
onmouseover:鼠标移进事件
onmouseout:鼠标移出事件
this关键字:在函数内部,this关键字表示当前操作元素
setAttribute(name,value):我们可以使用该方法来存储行原有的背景颜色,便于鼠标移出事件触发后恢复原有背景色
代码如下:
HTML代码:
<body>
<table id="tab" align="center" border="1px" cellspacing="0px" width="500px">
<thead>
<tr>
<th>编号</th>
<th>姓名</th>
<th>年龄</th>
</tr>
</thead>
<tbody>
<tr style="background-color: white;">
<td>1</td>
<td>张三</td>
<td>20</td>
</tr>
<tr style="background-color: white;">
<td>2</td>
<td>李四</td>
<td>20</td>
</tr>
<tr style="background-color: white;">
<td>3</td>
<td>王五</td>
<td>20</td>
</tr>
<tr style="background-color: white;">
<td>4</td>
<td>赵六</td>
<td>20</td>
</tr>
<tr style="background-color: white;">
<td>5</td>
<td>田七</td>
<td>20</td>
</tr>
</tbody>
</table>
</body>
JS代码:
<script language="JavaScript">
window.onload = function(){
var tabEle = document.getElementById("tab");
var allTr = tabEle.tBodies[0].getElementsByTagName("tr");
//为每一行绑定事件(鼠标移进与移出)
for(var i=0;i<allTr.length;i++){
//当鼠标移进时触发该事件
allTr[i].onmouseover = function(){
//保存好原有背景色
this.setAttribute("bgc",this.style.backgroundColor);
//修改背景色
this.style.backgroundColor = "yellow";
}
//当鼠标移出时触发该事件
allTr[i].onmouseout = function(){
//恢复原来的颜色
this.style.backgroundColor = this.getAttribute("bgc");
}
}
}
</script>