Which HTML elements can receive focus?

后端 未结 5 817
死守一世寂寞
死守一世寂寞 2020-11-22 00:20

I\'m looking for a definitive list of HTML elements which are allowed to take focus, i.e. which elements will be put into focus when focus() is called on them?<

5条回答
  •  温柔的废话
    2020-11-22 00:59

    There isn't a definite list, it's up to the browser. The only standard we have is DOM Level 2 HTML, according to which the only elements that have a focus() method are HTMLInputElement, HTMLSelectElement, HTMLTextAreaElement and HTMLAnchorElement. This notably omits HTMLButtonElement and HTMLAreaElement.

    Today's browsers define focus() on HTMLElement, but an element won't actually take focus unless it's one of:

    • HTMLAnchorElement/HTMLAreaElement with an href
    • HTMLInputElement/HTMLSelectElement/HTMLTextAreaElement/HTMLButtonElement but not with disabled (IE actually gives you an error if you try), and file uploads have unusual behaviour for security reasons
    • HTMLIFrameElement (though focusing it doesn't do anything useful). Other embedding elements also, maybe, I haven't tested them all.
    • Any element with a tabindex

    There are likely to be other subtle exceptions and additions to this behaviour depending on browser.

提交回复
热议问题