Lock tab key with javascript?

后端 未结 4 1194
野趣味
野趣味 2020-12-03 18:10

How to lock or disable and again the tab key with javascript?

4条回答
  •  感动是毒
    2020-12-03 18:35

    Expanding on Naftali aka Neal's answer, here's how you'd do it with vanilla JS and both start and stop Tab behavior buttons:

    let stopTabFunction = function(e) {
      if (e.keyCode == 9) {
        e.preventDefault();
      }
    };
    document.getElementById('stopTabButton').onclick = function() {
      document.addEventListener('keydown', stopTabFunction);
    };
    document.getElementById('resumeTabButton').onclick = function() {
      document.removeEventListener('keydown', stopTabFunction);
    };
    
    
    
    
    
    
    

    Note that this also works for Shift + Tab (reverse direction).

    JSFiddle


    However, in my case, I wanted slightly different behavior: I wanted to basically lock down Tab focus to a single div. To do this, I placed a div before and after it, gave them both tabindex="0" (document-defined tab order on the div's themselves), to make the outer edges of the div focusable, like so:

    Then, I changed the function from earlier to this:

    //Get the div's into variables etc.
    //...
    
    let forceTabFocusFunction = function (e) {
        if (e.keyCode == 9) {
            //Force focus onto the div.
            if (!myDiv.contains(document.activeElement)) {
                if (e.shiftKey) {
                    afterMyDiv.focus();
                } else {
                    beforeMyDiv.focus();
                }
            }
        }
    };
    

    That did the trick nicely.

提交回复
热议问题