How to make a custom web component focusable?

前端 未结 3 2098
时光取名叫无心
时光取名叫无心 2021-02-14 03:44

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 el

3条回答
  •  余生分开走
    2021-02-14 04:17

    Based on this demo that I found in this question, I have this answer:

    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.
    

    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.

    Also note that this.tabIndex returns -1 even if the HTML attribute is missing, but this has a different behavior than setting tabindex="1":

    • : No tabindex attribute, the element is not focusable.
    • : The element is not reachable through tab-navigation, but it is still focusable by clicking.

    References:

    • 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

提交回复
热议问题