如何使用CSS在TD内部使用元素覆盖TR?

时间:2017-04-12 11:51:43

标签: css

我有这张桌子,我希望在悬停时改变颜色,但当链接在TD内部时也会改变不同的颜色。

<table>
    <tr>
        <td>Hovering this part will make the whole TR bgcolor red</td>
        <td>Hovering this part will make the whole TR bgcolor red</td>
        <td>Hovering this part will make the whole TR bgcolor red</td>
    </tr>

    <tr>
        <td>Hovering this part will make the whole TR bgcolor red</td>
        <td>Hovering this part will make the whole TR bgcolor red</td>
        <td>Hovering this part will make the whole TR bgcolor red</td>
    </tr>

    <tr>
        <td>Hovering this part will make the whole TR bgcolor red</td>
        <td>Hovering this part will make the whole TR bgcolor red</td>
        <td>
            <a>HOVERING THIS LINK WILL MAKE WHOLE TR BG COLOR BLUE</a>
        </td>
    </tr>
</table>

我试过CSS

table tr:hover:not(table td a) {
    background-color: red !important;
}

table tr:hover{ 
    background-color: blue;
}

但我没有运气。 这可能不使用Javascript / Jquery吗?

2 个答案:

答案 0 :(得分:1)

您可以使用tr下面的伪元素来绘制背景。

z-index会设法将它们堆放在内容中。

示例:

&#13;
&#13;
table tr {
  position: relative;
}

table tr a:before,
tr:before {
  content: '';
  position: absolute;
  float:left;
  top: 0;
  left: 0;
  bottom: 0;
  right: 0;
  z-index: -2;
}
table tr:hover:before {
  background: red;  
}

table tr a:hover:before {
  z-index: -1;
  background-color: blue;
}

/*and  eventually: */a {display:block;background:rgba(0,0,0,0.0001);}a:hover {color:white;}
&#13;
<table>
    <tr>
        <td>Hovering this part will make the whole TR bgcolor red</td>
        <td>Hovering this part will make the whole TR bgcolor red</td>
        <td>Hovering this part will make the whole TR bgcolor red</td>
    </tr>

    <tr>
        <td>Hovering this part will make the whole TR bgcolor red</td>
        <td>Hovering this part will make the whole TR bgcolor red</td>
        <td>Hovering this part will make the whole TR bgcolor red</td>
    </tr>

    <tr>
        <td>Hovering this part will make the whole TR bgcolor red</td>
        <td>Hovering this part will make the whole TR bgcolor red</td>
        <td>
            <a>HOVERING THIS LINK WILL MAKE WHOLE TR BG COLOR BLUE</a>
        </td>
    </tr>
</table>
&#13;
&#13;
&#13;

答案 1 :(得分:0)

如果没有一些JavaScript,你会这样做很不寻常。 但如果您真的想这样做,可以查看这些问题并亲自尝试。

Question 1

Question 2

希望我能帮忙......