如何使自定义Web组件具有可关注性? [英] How to make a custom web component focusable?
问题描述
我正在撰写一份旨在互动的自定义网络组件。如何告诉浏览器此自定义组件应该获得焦点?
I'm writing a custom web component that is meant to be interactive. How can I tell the browser that this custom component should receive focus?
我希望我的自定义元素...
I wish that my custom element…
- 可以集中注意力(通过标签导航);
- 可以在关注时收到按键;
- 可以匹配
:focus
pseudo -selector 。
- could be focused (by tab-navigation);
- could receive keypresses when focused;
- could be matched by
:focus
pseudo-selector.
我没有使用任何外部库,只使用普通的HTML5 API。
I'm not using any external library, just plain HTML5 APIs.
推荐答案
Based on this demo that I found in this question, I have this answer:
只需将 tabindex
属性添加到您想要关注的元素中。
Just add the tabindex
attribute to the elements you want to be focusable.
// Add this to createdCallback function:
if (!this.hasAttribute('tabindex')) {
// Choose one of the following lines (but not both):
this.setAttribute('tabindex', 0);
this.tabIndex = 0;
}
// The browser automatically syncs tabindex attribute with .tabIndex property.
单击元素将使焦点成为焦点。按下选项卡将起作用。在CSS中使用:focus
也可以。 keydown
和 keyup
事件有效,但 keypress
没有(但它已被弃用)。在Chrome 44和Firefox 40上测试。
Clicking on the element will give it focus. Pressing tab will work. Using :focus
in CSS will also work. keydown
and keyup
events work, although keypress
doesn't (but it's deprecated anyway). Tested on Chrome 44 and Firefox 40.
另请注意 this.tabIndex
返回 - 1
即使HTML属性丢失,但这与设置 tabindex =1
:
Also note that this.tabIndex
returns -1
even if the HTML attribute is missing, but this has a different behavior than setting tabindex="1"
:
-
< foo>< / foo>
:否tabindex
属性,该元素不可聚焦。 -
< foo tabindex = - 1>< / foo>
:通过选项卡导航无法访问该元素,但通过单击仍然可以调整该元素。
<foo></foo>
: Notabindex
attribute, the element is not focusable.<foo tabindex="-1"></foo>
: The element is not reachable through tab-navigation, but it is still focusable by clicking.
参考文献:
- http://www.w3.org/TR/html5/editing.html#sequential-focus-navigation-and-the-tabindex-attribute
- https://html.spec.whatwg .ORG /多页/ interaction.html#的-的TabIndex -attribute
- https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/tabindex
- https://github.com/whatwg/html/issues/113
- http://www.w3.org/TR/html5/editing.html#sequential-focus-navigation-and-the-tabindex-attribute
- https://html.spec.whatwg.org/multipage/interaction.html#the-tabindex-attribute
- https://developer.mozilla.org/en-US/docs/Web/HTML/Global_attributes/tabindex
- https://github.com/whatwg/html/issues/113
这篇关于如何使自定义Web组件具有可关注性?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!