如何将具有<td:active>的背景色设置为其他颜色?

时间:2019-03-03 22:57:55

标签: html css

在将“活动”类添加到特定<td>单元的事件期间,我想在该事件发生时将<tr>背景设置为不同的颜色。目前,我只能将所有<td>单元格设置为之后 <td:active>。我还要将<td>单元格设置为之前 <td:active>,从而使整行更改为不同的背景颜色。

表结构:

<table>
<tr>
  <td style="background: yellow"></td>
  <td style="background: yellow"></td>
  <td style="background: yellow"></td>
</tr>
<tr>
  <td style="background: yellow"></td>
  <td style="background: yellow"></td>
  <td style="background: yellow"></td>
</tr>
<tr>
  <td style="background: yellow"></td>
  <td style="background: yellow"></td>
  <td style="background: yellow"></td>
</tr>
</table>

预期:何时发生特定事件

<table>
<tr>
  <td style="background: yellow"></td>
  <td style="background: yellow"></td>
  <td style="background: yellow"></td>
</tr>
<tr> <!-- applied new css during the event -->
  <td style="background: blue"></td>
  <td class="active" style="background: blue"></td>
  <td style="background: blue"></td>
</tr>
<tr>
  <td style="background: yellow"></td>
  <td style="background: yellow"></td>
  <td style="background: yellow"></td>
</tr>
</table>

实际:事件发生时

<table>
<tr>
  <td style="background: yellow"></td>
  <td style="background: yellow"></td>
  <td style="background: yellow"></td>
</tr>
<tr> <!-- applied new css during the event -->
  <td style="background: yellow"></td>
  <td class="active" style="background: blue"></td>
  <td style="background: blue"></td>
</tr>
<tr>
  <td style="background: yellow"></td>
  <td style="background: yellow"></td>
  <td style="background: yellow"></td>
</tr>
</table>

我想在事件发生时修复我当前的CSS样式(以实现“预期”),但是我不知道任何正确的CSS逻辑/语法。

2 个答案:

答案 0 :(得分:0)

我用$('td.active')。parent()。children()。css('background','blue');然后它按我的预期工作。

答案 1 :(得分:0)

由于您没有任何可与我们一起使用的代码,因此这是我刚刚编写的一个小示例。与其将类添加到td中,不如将其添加到tr中吗?通过CSS可以轻松处理它。有了它,您可以定义一个以上的类并根据您的喜好/要求添加。

下面的示例是向tr添加一个类,其余的都通过CSS完成:

$(document).ready(function() {
  $( 'table tr' ).hover(function() {
    $('table tr').removeClass('active');
    $(this).addClass('active');
  });
});
td{background-color:#ff0;}
tr.active td{background-color:#f00;}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
  <td>&nbsp;</td>
  <td>&nbsp;</td>
  <td>&nbsp;</td>
</tr>
<tr>
  <td>&nbsp;</td>
  <td>&nbsp;</td>
  <td>&nbsp;</td>
</tr>
<tr>
  <td>&nbsp;</td>
  <td>&nbsp;</td>
  <td>&nbsp;</td>
</tr>
</table>

上面的代码目前可以在悬停上使用,但是您可以根据需要将其更改为单击。

欢呼