撰写:2020年1月14日
注意:不能保证三五年后,本博文对于新版的浏览器和jQuery仍然有效,请斟酌参考!
一、系统环境
- Windows 10 64bit 1903
- Chrome 79 64bit
- jQuery 3.4.1
二、代码
2.1 创建样板html
使用VS Code创建一个包含表格的html文件:
鼠标悬停变色
1
前端开发中经常使用到table表格
前端开发中经常使用到table表格
前端开发中经常使用到table表格
2
前端开发中经常使用到table表格
前端开发中经常使用到table表格
前端开发中经常使用到table表格
3
前端开发中经常使用到table表格
前端开发中经常使用到table表格
前端开发中经常使用到table表格
4
前端开发中经常使用到table表格
前端开发中经常使用到table表格
前端开发中经常使用到table表格
5
前端开发中经常使用到table表格
前端开发中经常使用到table表格
前端开发中经常使用到table表格
将上述代码保存为悬停变色.html,双击该文件,即可在浏览器中看到如下显示结果:
2.2 引入jQuery
可以使用CDN引入jQuery,CDN的网址如下:https://www.bootcdn.cn/jquery/,打开该网址,复制最新的3.4.1到剪贴板,将其加入到html的head标签内。引入jQuery的代码如下:
2.3 hover实现悬停变色
实现表格行悬停变色,可以采用jQuery中的hover事件。hover的语法如下:
$( selector ).hover( handlerIn, handlerOut )
其中selector为选择器,handerIn为鼠标进入时的回调函数,handerOut为鼠标离开时的回调函数。
在悬停变色.html的head标签中新建一个script标签,其中代码如下:
$(document).ready(function(){
$("table#DataGrid1 tr").hover(function () {
$(this).css("background-color", "yellow");
}, function () {
$(this).css("background-color", "white");
});
});
上面这部分代码实现了当鼠标进入时,表格行背景色变为黄色,鼠标离开时表格行背景色变为白色。
效果如下:
2.4 完整代码如下:
鼠标悬停变色
1
前端开发中经常使用到table表格
前端开发中经常使用到table表格
前端开发中经常使用到table表格
2
前端开发中经常使用到table表格
前端开发中经常使用到table表格
前端开发中经常使用到table表格
3
前端开发中经常使用到table表格
前端开发中经常使用到table表格
前端开发中经常使用到table表格
4
前端开发中经常使用到table表格
前端开发中经常使用到table表格
前端开发中经常使用到table表格
5
前端开发中经常使用到table表格
前端开发中经常使用到table表格
前端开发中经常使用到table表格