有没有办法禁用 div 及其子节点的焦点?

da0*_*B0y 6 html javascript css

假设我们有一个 DOM:

...
<div>
  // child nodes
</div>
<div id="needsToNotBeFocusable"> 
  // child nodes 
</div>
...
Run Code Online (Sandbox Code Playgroud)

有没有办法使其<div id="needsToNotBeFocusable">及其子节点不可聚焦?

tabindex="-1"每个子节点上的设置都会破坏已经存在的选项卡索引。

jun*_*var 2

首先,“无法通过 Tab 键聚焦”和“永远无法聚焦(以编程方式、通过单击或通过 Tab 键)”之间存在区别。前者是通过设置tabindex="-1"属性来实现的,后者是通过添加disabled属性来实现的。

input {display:block}
Run Code Online (Sandbox Code Playgroud)
<input>
<input>
disabled: <input disabled>
tab -1: <input tabindex="-1">
<input>
<input>
Run Code Online (Sandbox Code Playgroud)

在每个子节点上设置 tabindex="-1" 将破坏已经存在的 tabindexes。

我不明白你的意思。tabindex 是如何被不可聚焦的元素破坏的呢?

有没有办法使其及其子节点不可聚焦?

Div 不能在正常意义上聚焦(尽管它们可以滚动到)。但要使其子级无法聚焦,只需要迭代其子级(可能深达多个级别)并使用 settinttabindexdisabled.

let recursiveUnfocusable = el => {
  el.disabled = true;
  [...el.children].forEach(recursiveUnfocusable);
};

let div = document.querySelector('#needsToNotBeFocusable');
recursiveUnfocusable(div);
Run Code Online (Sandbox Code Playgroud)
...
<div>
  <input><input><input>
</div>
<div id="needsToNotBeFocusable"> 
  <input><input><input>
  <div>
    <input><input><input>
  </div>
</div>
...
Run Code Online (Sandbox Code Playgroud)