CSS:表格 - 带colspan的行 - 鼠标悬停时更改整行颜色

5

希望这篇文章没有重复。我希望当鼠标停留在 tr[child]:hover 上时,整行都会变颜色。

<!DOCTYPE html>
<html>
<head>
 <title></title>
 <style type="text/css">

  tr[origin]:hover {
   background-color: grey;
  }

  tr[origin]:hover + tr[child]{
   background-color: grey;
  }

  tr[child]:hover {
   background-color: grey;
  }

 </style>
</head>
<body>
 <table border="1px">

  <tr origin>
   <td rowspan="2">1</td>
   <td colspan="2">Question</td>
   <td rowspan="2">2/3</td>
   <td rowspan="2">View answer</td>
  </tr>
  <tr child>
   <td>Rasp 1</td>
   <td>Rasp2</td>
  </tr>

  <tr origin>
   <td rowspan="2">1</td>
   <td colspan="2">Question</td>
   <td rowspan="2">2/3</td>
   <td rowspan="2">View answer</td>
  </tr>
  <tr child>
   <td>Rasp 1</td>
   <td>Rasp2</td>
  </tr>
 </table>
</body>
</html>


CSS在这里无能为力。CSS没有向上选择器,它只能选择下一个兄弟元素。你可以使用[child]:hover + tr {background:..},但是[child]:hover - tr {background:..}不存在 :) - G-Cyrillus
为什么W3C还没有采用“前一个兄弟选择器”呢?感到遗憾。 - user8555937
对于与父选择器.级联的相同问题,需要在文档的每个标签中来回遍历HTML树,这将需要大量资源。 - G-Cyrillus
2个回答

2
这是一个非常有趣的问题!您可以使用 tbody 来实现。根据 w3 的 规范,您可以在表格中放置多个 tbody。引用规范中的内容:“表格行可以分组为表头、表尾和一个或多个表体节...”

tbody:hover {
  background-color: #CCCCCC;
}
<table border="1px">

  <tbody>
    <tr origin>
      <td rowspan="2">1</td>
      <td colspan="2">Question</td>
      <td rowspan="2">2/3</td>
      <td rowspan="2">View answer</td>
    </tr>
    <tr child>
      <td>Rasp 1</td>
      <td>Rasp2</td>
    </tr>
  </tbody>

  <tbody>
    <tr origin>
      <td rowspan="2">1</td>
      <td colspan="2">Question</td>
      <td rowspan="2">2/3</td>
      <td rowspan="2">View answer</td>
    </tr>
    <tr child>
      <td>Rasp 1</td>
      <td>Rasp2</td>
    </tr>
  </tbody>

</table>


1

将每行的td元素包装在tbody中,并在css中定位它:

<!DOCTYPE html>
<html>
<head>
    <title></title>
    <style type="text/css">

        tbody[row]:hover {
            background-color: grey;
        }

    </style>
</head>
<body>
    <table border="1px">
      <tbody row>
        <tr origin>
            <td rowspan="2">1</td>
            <td colspan="2">Question</td>
            <td rowspan="2">2/3</td>
            <td rowspan="2">View answer</td>
        </tr>
        <tr child>
            <td>Rasp 1</td>
            <td>Rasp2</td>
        </tr>
      </tbody>
      <tbody row>
        <tr origin>
            <td rowspan="2">1</td>
            <td colspan="2">Question</td>
            <td rowspan="2">2/3</td>
            <td rowspan="2">View answer</td>
        </tr>
        <tr child>
            <td>Rasp 1</td>
            <td>Rasp2</td>
        </tr>
      </tbody>
    </table>
</body>
</html>


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接