html - 如何使自定义 Web 组件可聚焦?

标签 html web-component

我正在写一个 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 中也可以。 keydownkeyup事件有效,虽然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/

相关文章:

javascript - 文本节点可以开槽吗?

javascript - 导入 "wrong"顺序的Web组件时出错

java - 如何在java中获取url html内容到字符串

javascript - CSS :after fails in IE8, 但仅在添加对 jQuery 的引用之后

html - 响应式文本框

javascript - 处理 polymer 元素继承的最佳方法

web-component - 微软的 X-Tag 与 Mozilla 的 X-Tags

html - 奇怪的媒体查询行为

html - 宽度百分比不适用于 div

javascript - HTML 在 Internet Explorer 中导入加载顺序