css - 如何将焦点添加到表格行 <tr>?

标签 css angularjs html-table focus

我有一个用 生成的表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'
   });
});

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

最佳答案

:focus伪类仅适用于表单元素,例如 <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>

关于css - 如何将焦点添加到表格行 <tr>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50492141/

相关文章:

c# - autogeneratecolumns=true 时如何实现 wrap 属性?

html - 如何在css中播放动画后更改按钮颜色

javascript - Highchart 事件量表始终在中心显示文本

javascript - 像图片中那样在css中制作下拉菜单

AngularJs ng-if 比较日期

javascript - 如何在 Angular JS 中将参数传递给模态

jquery - 为什么我无法使用 jQuery 在 IE 中淡出该表行?

html - Angular JS : updating object values in scope after the backend call

php - 如何在 PHP 中对 Mysql 表进行分页

html - 如何摆脱表格中的额外高度