【问题标题】:CSS :focus selector doesn't work when element is focused with .focus()当元素以 .focus() 为焦点时,CSS :focus 选择器不起作用
【发布时间】:2017-05-14 05:48:46
【问题描述】:

我试图突出重点关注<tr>s。

我已经为它们每个添加了一个-1 的tabindex,并确认调用some_tr.focus()document.activeElement 设置为some_tr。但是,由于某种原因,some_tr 没有被 tr:focus CSS 规则突出显示。

需要注意的是,对于我 (Firefox 54),手动单击 <tr>确实会使其突出显示。

document.getElementById("that_tr").focus();
console.log(document.activeElement);
tr:focus {
  background:lightblue;
}
<table>
  <tr>
    <th>part</th>
    <th>peice</th>
    <th>thing</th>
    <th>stuff</th>
  </tr>
  <tr tabindex="-1">
    <td><span>data1</span></td>
    <td><span>data1</span></td>
    <td><span>data1</span></td>
    <td><span>data1</span></td>
  </tr>
  <tr id="that_tr" tabindex="-1">
    <td><span>data2</span></td>
    <td><span>data2</span></td>
    <td><span>data2</span></td>
    <td><span>data2</span></td>
  </tr>
</table>

为什么that_tr 在上面的 sn-p 中没有突出显示?我怎样才能让它工作?

【问题讨论】:

  • 我在运行您的 sn-p 时看到突出显示。
  • 它适用于 Chrome、Safari 和 Firefox。
  • 我可以确认它在 Firefox 54.0a2 中不起作用
  • @Barmar 单击“运行代码 sn-p”后,最后一个 tr 会以浅蓝色突出显示?
  • @IiroP 那么这是浏览器错误吗..?

标签: javascript html css html-table focus


【解决方案1】:

我不知道为什么,但我发现我的代码在从事件侦听器运行时对我有用(Linux 上的 Firefox)。这似乎是浏览器的一个怪癖,也可能是一个错误。

document.addEventListener('keydown', function(e) {
  document.getElementById("that_tr").focus();
  console.log(document.activeElement);
});
tr:focus {
  background:lightblue;
}
<table>
  <tr>
    <th>part</th>
    <th>peice</th>
    <th>thing</th>
    <th>stuff</th>
  </tr>
  <tr tabindex="-1">
    <td><span>data1</span></td>
    <td><span>data1</span></td>
    <td><span>data1</span></td>
    <td><span>data1</span></td>
  </tr>
  <tr id="that_tr" tabindex="-1">
    <td><span>data2</span></td>
    <td><span>data2</span></td>
    <td><span>data2</span></td>
    <td><span>data2</span></td>
  </tr>
</table>

这对我来说已经足够好了,因为无论如何我都打算在事件侦听器中运行它。也就是说,我不介意了解这种行为的原因(如果有的话)。

【讨论】:

    猜你喜欢
    • 2023-04-02
    • 1970-01-01
    • 1970-01-01
    • 2013-07-05
    • 1970-01-01
    • 2023-04-03
    • 2021-12-31
    • 2015-08-15
    • 1970-01-01
    相关资源
    最近更新 更多