Preventing tab to cycle through address bar

前端 未结 8 1492
一生所求
一生所求 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:40

    You could use Javascript and capture the "keydown" event on the element with the highest "tabindex". If the user presses the "TAB" key (event.keyCode==9) without the "Shift" key (event.shiftKey == false) then simply set the focus on the element with the lowest tabindex.

    You would then also need to do the same thing in reverse for the element with the lowest tabindex. Capture the "keydown" event for this element. If the user presses the "TAB" key (event.keyCode==9) WITH the "Shift" key (event.shiftKey == true) then set the focus on the element with the highest tabindex.

    This would effectively prevent the address bar from ever being focused using the TAB key. I am using this technique in my current project.

    Dont forget to cancel the keydown event if the proper key-combination is pressed! With JQuery it's "event.preventDefault()". In standard Javascript, I believe you simply "return false".

    Here's a JQuery-laden snippet I'm using...

        $('#dos-area [tabindex=' + maxTabIndex + ']').on('keydown', function (e) {
            if (e.keyCode == 9 && e.shiftKey == false) {
                e.preventDefault();
                $('#dos-area [tabindex=1]').focus();
            }
        });
        $('#dos-area [tabindex=1]').on('keydown', function (e) {
            if (e.keyCode == 9 && e.shiftKey == true) {
                e.preventDefault();
                $('#dos-area [tabindex=' + maxTabIndex + ']').focus();
            }
        });
    

    Also keep in mind that setting tabindex=0 has undesirable results on the order in which things are focused. I always remember (for my purposes) that tabindex is a 1-based index.

提交回复
热议问题