如何将焦点添加到表行< tr&gt ;? [英] How to add Focus to a table row <tr>?

查看:178
本文介绍了如何将焦点添加到表行< tr&gt ;?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个用 AngularJS 生成的表.
这是我的HTML:

I have a table generated with AngularJS.
Here's my 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进行此操作:

I want each row to change color when "hover" and a different color when "clicked", so I tried this with 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>

悬停效果很好,但是焦点不起作用! (奇怪的是,在浏览器控制台中,如果我选择该行并选择" force element state:focus ",那么它将焦点应用于该行)

The hover works perfectly, but the Focus is not working! (The weird thing is that in the browser console, if I select the row and "force element state :focus" then it applies the focus to the row)

我也尝试过将SCRIPT与jquery一起使用:

I also tried using a SCRIPT with jquery:

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

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

But this won't work too, what am I doing wrong?

推荐答案

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

The :focus pseudo class only works with form elements such as <input>, <button> etc. You can add it to a non-form element like <tr> by adding tabindex, e.g.:

<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>

这篇关于如何将焦点添加到表行&lt; tr&gt ;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆