a[href]:not([tabindex='-1']),
area[href]:not([tabindex='-1']),
input:not([disabled]):not([tabindex='-1']),
select:not([disabled]):not([tabindex='-1']),
textarea:not([disabled]):not([tabindex='-1']),
button:not([disabled]):not([tabindex='-1']),
iframe:not([tabindex='-1']),
[tabindex]:not([tabindex='-1']),
[contentEditable=true]:not([tabindex='-1'])
{
/* your CSS for focusable elements goes here */
}
或者在SASS中更美丽一点:
a[href],
area[href],
input:not([disabled]),
select:not([disabled]),
textarea:not([disabled]),
button:not([disabled]),
iframe,
[tabindex],
[contentEditable=true]
{
&:not([tabindex='-1'])
{
/* your SCSS for focusable elements goes here */
}
}
$focusable:
'a[href]',
'area[href]',
'button',
'details',
'input',
'iframe',
'select',
'textarea',
// these are actually case sensitive but i'm not listing out all the possible variants
'[contentEditable=""]',
'[contentEditable="true"]',
'[contentEditable="TRUE"]',
'[tabindex]:not([tabindex^="-"])',
':not([disabled])';
6 回答
浏览器还没有't a definite list, it' . 我们唯一的标准是DOM Level 2 HTML,根据该标准,具有
focus()
方法的唯一元素是HTMLInputElement,HTMLSelectElement,HTMLTextAreaElement和HTMLAnchorElement . 这显然省略了HTMLButtonElement和HTMLAreaElement .今天的浏览器在HTMLElement上定义了
focus()
,但是一个元素赢得了_1857490的s:带有href的HTMLAnchorElement / HTMLAreaElement
HTMLInputElement / HTMLSelectElement / HTMLTextAreaElement / HTMLButtonElement但不包含
disabled
(如果您尝试,IE实际上会给您一个错误),并且出于安全原因,文件上传有异常行为HTMLIFrameElement(虽然重点关注它并没有对它们进行全面测试 .
任何带有
tabindex
的元素根据浏览器的不同,这种行为可能会有其他细微的例外和补充 .
这里我有一个基于bobince的answer的CSS选择器来选择任何可聚焦的HTML元素:
或者在SASS中更美丽一点:
我已经添加了它作为答案,因为那就是我正在寻找的,当Google将我重定向到这个Stackoverflow问题时 .
EDIT: 还有一个选择器,它是可聚焦的:
但是,很少使用它 .
ally.js辅助功能库提供了一个非官方的,基于测试的列表:
https://allyjs.io/data-tables/focusable.html
(注意:他们的页面没有说明测试的执行频率 . )
我正在创建一个包含所有可聚焦元素的SCSS列表,我认为这可能有助于某人因为这个问题的谷歌排名 .
有几点需要注意:
我将
:not([tabindex="-1"])
更改为:not([tabindex^="-"])
因为以某种方式生成-2
非常合理 . 比抱歉更安全吗?将
:not([tabindex^="-"])
添加到所有其他可聚焦选择器是完全没有意义的 . 当使用[tabindex]:not([tabindex^="-"])
时,它已经包含了你用:not
否定的所有元素!我包含了
:not([disabled])
因为禁用的元素永远不可聚焦 . 所以再次将它添加到每个元素都没用 .也许这个可以帮助:
返回值:true =成功,false =失败
Reff:https://developer.mozilla.org/en-US/docs/Web/API/DocumentOrShadowRoot/activeElement https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/focus
http://www.w3schools.com/cssref/sel_focus.asp