Preventing tab to cycle through address bar

前端 未结 8 1539
一生所求
一生所求 2021-02-20 06:54

I realize this is probably an accessibility issue that may best be left alone, but I\'d like to figure out if it possible to prevent the tab from visiting the address bar in the

8条回答
  •  失恋的感觉
    2021-02-20 07:36

    Here's a generic jquery implementation where you don't have to find the max tab index. Note that this code will also work if you add or remove elements in your DOM.

    $('body').on('keydown', function (e) {
        var jqTarget = $(e.target);
        if (e.keyCode == 9) {
    
            var jqVisibleInputs = $(':input:visible');
            var jqFirst = jqVisibleInputs.first();
            var jqLast = jqVisibleInputs.last();
    
            if (!e.shiftKey && jqTarget.is(jqLast)) {
                e.preventDefault();
                jqFirst.focus();
            } else if (e.shiftKey && jqTarget.is(jqFirst)) {
                e.preventDefault();
                jqLast.focus();
            }
        }
    });
    

    However, you should note that the code above will work only with visible inputs. Some elements may become the document's activeElement even if they're not input so if it's your case, you should consider adding them to the $(':input:visible') selector.

    I didn't add code to scroll to the focus element as this may not be the wanted behavior for everyone... if you need it, just add it after the call to focus()

提交回复
热议问题