我正在写一个 custom web component那意味着是互动的。我如何告诉浏览器这个自定义组件应该获得焦点?
我希望我的自定义元素......
- 可以集中注意力(通过标签导航);
- 在聚焦时可以接收按键;
- 可以匹配
:focus
pseudo-selector .
我没有使用任何外部库,只使用普通的 HTML5 API。
最佳答案
基于 this demo我在 this question 中找到的,我有这个答案:
只需添加 tabindex
属性到您希望可聚焦的元素。
// 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.
点击该元素将获得焦点。按选项卡将工作。使用 :focus
在 CSS 中也可以。 keydown
和 keyup
事件有效,虽然keypress
没有(但是 it's deprecated anyway )。在 Chrome 44 和 Firefox 40 上测试。
另请注意 this.tabIndex
返回 -1
即使缺少 HTML 属性,但这与设置 tabindex="1"
的行为不同:
-
<foo></foo>
: 没有tabindex
属性,该元素不可聚焦。 -
<foo tabindex="-1"></foo>
: 该元素无法通过选项卡导航访问,但仍可通过单击获得焦点。
引用资料:
关于html - 如何使自定义 Web 组件可聚焦?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32417235/