好吧,我有一个奇怪的需求。我并不是试图将焦点捕获在特定的 div 内,而是试图阻止它进入特定的其他 div。我有一个脚本,可以将 div 上的类从焦点上的“折叠”更改为“展开”。当 div 具有“expanded”类时,我希望人们能够专注于其内部的元素,并将其外部的 Tab 切换到页面的其他区域,但不能进入具有“collapsed”类的 div 。所以这是一个假设的样本:
<nav>
<a href="#one">One</a>
<a href="#two">One</a>
<a href="#three">One</a>
</nav>
<div id="one" tabindex="-1" class="collapsed">
Prevent focus on elements on this div or on elements inside it
<button>Button</button>
<div>
<div id="two" tabindex="-1" class="expanded">
Allow focus in this div and to focus outside of it
<button>Button</button>
<div>
<div id="three" tabindex="-1" class="collapsed">
Prevent focus on elements on this div or on elements inside it
<button>Button</button>
<div>
<p>When focus is set on div two, pressing tab key should go to the button inside it, and then to this link: <a href="#">test link</a></p>
我该怎么做?
这可以通过向折叠的 div 添加
inert
属性来完成。除了设置展开/折叠类之外,您还需要添加/删除此属性。
例如:
<html>
<nav>
<a href="#one">One</a>
<a href="#two">One</a>
<a href="#three">One</a>
</nav>
<div id="one" tabindex="-1" class="collapsed" inert>
Prevent focus on elements on this div or on elements inside it
<button>Button</button>
</div>
<div id="two" tabindex="-1" class="expanded">
Allow focus in this div and to focus outside of it
<button>Button</button>
</div>
<div id="three" tabindex="-1" class="collapsed" inert>
Prevent focus on elements on this div or on elements inside it
<button>Button</button>
</div>
<p>When focus is set on div two, pressing tab key should go to the button inside it, and then to this link: <a href="#">test link</a></p>
</html>
注意:假设示例中的 div 未用
关闭