如何使自定义Web组件具有可关注性? [英] How to make a custom web component focusable?

查看:107
本文介绍了如何使自定义Web组件具有可关注性?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在撰写一份旨在互动的自定义网络组件。如何告诉浏览器此自定义组件应该获得焦点?

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…

  • 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>: No tabindex 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/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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆