首页 > 解决方案 > 有没有一种快速的方法可以从类或类型的所有元素中删除选项卡焦点?

问题描述

假设我有 2 个按钮,一个输入和一个文本区域,我知道如何设置tabindex="-1"以防止分别为每个按钮设置标签。

有没有一种快速的方法可以防止我体内的所有按钮都具有选项卡焦点,或者一个类的所有元素(例如类“foo”的所有元素)?

我也对 js 建议持开放态度。

<html>
<body>
<button>BUTTON 1</button><button class="foo">BUTTON 2</button>
<input class="foo">
<textarea></textarea>
</body>
</html>

标签: javascripthtmlcss

解决方案


以编程方式设置怎么样tabindex="-1"

var unfocusableElems = document.querySelectorAll('button, input, textarea, .foo');
unfocusableElems.forEach(function (el) { el.setAttribute('tabindex', '-1'); });
<html>
<body>
<button>BUTTON 1</button><button class="foo">BUTTON 2</button>
<input class="foo">
<textarea></textarea>
</body>
</html>


推荐阅读