如何为表格行<tr>添加焦点?

6

我有一个使用AngularJS生成的表格。
这是我的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>

我希望每一行在“悬停”时改变颜色,在“点击”时改为另一种颜色,因此我尝试使用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>

悬停效果正常,但焦点无法正常工作!(奇怪的是,在浏览器控制台中,如果我选择该行并"强制元素状态:焦点",那么它会将焦点应用于该行)。
我还尝试使用带有jquery的SCRIPT:
$(document).ready(function() {
   $('.my_table tbody tr').click(function() {
      $(this).addClass('active'); //I'm adding the color gray with css to '.active'
   });
});

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

可能是Angular.js:输入聚焦时设置CSS的重复问题。 - Aleksey Solovey
https://dev59.com/Mmkw5IYBdhLWcg3wEmab 这个可能有所帮助,希望对您有用 :) - UnpassableWizard
@AlekseySolovey 那个重复问题与此无关,因为这不涉及输入元素。 - Sterling Archer
2个回答

25
:focus 伪类仅适用于表单元素,如 <input><button> 等。您可以通过添加 tabindex 将其添加到非表单元素中,例如:<tr>
<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>


我不知道这个..非常感谢,这个很好用! - Soul Eater
哇,这真不直观!谢谢。 - Debbie A

-1
我会使用指令:

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

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