Make an HTML element non-focusable

前端 未结 8 2293
误落风尘
误落风尘 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:14

    For the element you do not want to be focused on tab, you have to put the tabindex as a negative value.

    0 讨论(0)
  • 2020-12-02 17:14

    Making a focusable-by-default HTML element a non-focusable one isn't possible without JavaScript.

    After diving into focus-related DOM events, I've came up with the following implementation (based on the @ShortFuse's answer, but fixed some issues and edge cases):

        // A focus event handler to prevent focusing an element it attached to
        onFocus(event: FocusEvent): void {
            event.preventDefault();
    
            // Try to remove the focus from this element.
            // This is important to always perform, since just focusing the previously focused element won't work in Edge/FF, if that element is unable to actually get the focus back (became invisible, etc.): the focus would stay on the current element in such a case
            const currentTarget: any | null = event.currentTarget;
            if (currentTarget !== null && isFunction(currentTarget.blur))
                currentTarget.blur();
    
            // Try to set focus back to the previous element
            const relatedTarget: any | null = event.relatedTarget;
            if (relatedTarget !== null && isFunction(relatedTarget.focus))
                relatedTarget.focus();
        }
    
       // Not the best implementation, but works for the majority of the real-world cases
        export function isFunction(value: any): value is Function {
            return value instanceof Function;
        }
    

    This is implemented in TypeScript, but could be easily adjusted for plain JavaScript.

    0 讨论(0)
提交回复
热议问题