当鼠标移动到表格的一行时这一行的背景颜色发生改变

本文介绍两种实现鼠标悬停在HTML表格行上时背景颜色发生变化的方法。一种是使用CSS伪类:hover来改变行背景颜色;另一种是在<tr>标签内使用onmouseover和onmouseout事件直接修改样式。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

当鼠标移动到表格的一行时这一行的背景颜色发生改变

方法一:

<!DOCTYPE html>
<html>
 <head>
  <meta charset="utf-8">
  <title>当鼠标经过表格的一行时这一行的背景颜色发生改变</title>
  <style type="text/css">
   table, th, tr, td{
    width:500px;
    border:1px solid red;
    border-collapse:collapse;
   }
   tr, td{
    text-align:center;
    height:50px;
    /*line-height:35px; 和 height都可以表示文字在表格中垂直居中*/
   }
   tr:hover{
    background:#cccccc;
   }

  </style>
 </head>
 <body>
 <!--放在table中的属性width="500" border="1" bgcolor="#b4b4b4" align="center" style="border-collapse:collapse;" cellspacing="0" cellpadding="0"-->
  <table  >
  <thead>
  <tr>
    <th>学号</th>
    <th>姓名</th>
    <th>数学</th>
    <th>语文</th>
  </tr>
  </thead>
  <tbody>
  <tr>
    <td>001</td>
    <td>张三</td>
    <td>92</td>
    <td>98</td>
  </tr>
  <tr>
    <td>002</td>
    <td>李四</td>
    <td>99</td>
    <td>88</td>
  </tr>
  </tbody>
  </table>
 </body>
</html>

方法2:

<!DOCTYPE html>
<html>
 <head>
  <meta charset="utf-8">
  <title>当鼠标经过表格的一行时这一行的背景颜色发生改变方法2</title>
  <style>
   table, th, tr, td{
   width:500px;
    border:1px solid red;
    border-collapse:collapse;
   }
    tr, td{
     text-align:center;
     line-height:50px;

    }
  </style>
 </head>
 <body>
  <table  >
  <thead>
  <tr οnmοuseοver="this.style.background='gray'" οnmοuseοut="this.style.background='white'">
    <th>学号</th>
    <th>姓名</th>
    <th>数学</th>
    <th>语文</th>
  </tr>
  </thead>
  <tbody>
  <tr οnmοuseοver="this.style.background='gray'" οnmοuseοut="this.style.background='white'">
    <td>001</td>
    <td>张三</td>
    <td>92</td>
    <td>98</td>
  </tr>
  <tr οnmοuseοver="this.style.background='gray'" οnmοuseοut="this.style.background='white'">
    <td>002</td>
    <td>李四</td>
    <td>99</td>
    <td>88</td>
  </tr>
  <tr οnmοuseοver="this.style.background='gray'" οnmοuseοut="this.style.background='white'">
    <td>003</td>
    <td>张华</td>
    <td>92</td>
    <td>90</td>
  </tr>
  </tbody>
  </table>
 </body>
</html>

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值