【JS学习总结】如何使用JS实现表格高亮显示

前言:这个系列主要是对之前学习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>

 

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值