Make an HTML element non-focusable

前端 未结 8 2317
误落风尘
误落风尘 2020-12-02 16:40

Is it possible to make an HTML element non-focusable?

I understand that a list of elements that can receive focus can be defined and that a user can

8条回答
  •  执念已碎
    2020-12-02 17:04

    In order to make an prevent an element from taking focus ("non-focusable"), you need to use Javascript to watch for the focus and prevent the default interaction.

    In order to prevent an element from being tabbed to, use tabindex=-1 attribute.

    Adding tabindex=-1 will make any element focusable, even div elements. This means when a user clicks on it, it would likely get a focus outline, depending on the browser..

    You would ideally, want this:

    function preventFocus(event) {
      event.preventDefault();
      if (event.relatedTarget) {
        // Revert focus back to previous blurring element
        event.relatedTarget.focus();
      } else {
        // No previous focus target, blur instead
        event.currentTarget.blur();
      }
    }
    
    /* ... */
    
    element.setAttribute('tabindex', '-1');
    element.addEventListener('focus', preventFocus);
    

提交回复
热议问题