如何将焦点添加到 table 行 <tr>?

How to add Focus to a table row <tr>?

我用 AngularJS.
生成了一个 table 这是我的 HTML:

<table class="my_table">
    <thead>
         <tr>
            <th>Name</th>
            <th>Address</th>
            <th>Celphone</th>
        </tr>
    </thead>
    <tbody>
        <tr ng-repeat="contact in contacts">
            <td>{{contact.Name}}</td>
            <td>{{contact.Address}}</td>
            <td>{{contact.Celphone}}</td>
        </tr>
    </tbody>
</table>

我希望每一行在 "hover" 时改变颜色,在 "clicked" 时改变颜色,所以我用 CSS:

尝试了这个
<style>
.my_table tbody tr:hover {
   background-color: #7fccee; /*--- this is a blue color when hover ---*/
}
.my_table tbody tr:focus {
   background-color: #f3f3f3; /*--- this is a gray color when clicked---*/
}
</style>

悬停效果很好,但 焦点 不起作用! (奇怪的是,在浏览器控制台中,如果我 select 该行和“force element state :focus” 然后它将焦点应用到该行)

我也尝试过使用脚本 jquery:

$(document).ready(function() {
   $('.my_table tbody tr').click(function() {
      $(this).addClass('active'); //I'm adding the color gray with css to '.active'
   });
});

但这也不行,我做错了什么?

:focus 伪 class 仅适用于表单元素,例如 <input><button> 等。您可以将其添加到非表单元素,例如 <tr> 添加 tabindex,例如:

<tr tabindex="0">

然后照常应用 CSS。

.my_table tbody tr:hover {
  background-color: blue;
}

.my_table tbody tr:focus {
  background-color: red;
  outline: 0; /*remove outline*/
}
<table class="my_table" border>
  <thead>
    <tr>
      <th>Name</th>
      <th>Address</th>
      <th>Celphone</th>
    </tr>
  </thead>
  <tbody>
    <tr ng-repeat="contact in contacts" tabindex="0">
      <td>{{contact.Name}}</td>
      <td>{{contact.Address}}</td>
      <td>{{contact.Celphone}}</td>
    </tr>
  </tbody>
</table>

我会使用指令:

app.directive('ngFocusClass', function () {
  return ({
        restrict: 'A',
        link: function(scope, element) {
            element.focus(function () {
                element.addClass('focus');
            });
            element.blur(function () {
                element.removeClass('focus');
            });
        }
    });
});