简体   繁体   中英

Javascript: trap focus in dialog

I have a popup dialog (a div with a high z-index) which contains some input elements. While this dialog is open, I'd like tab and shift-tab to only cycle between elements in this dialog. How can I accomplish this?

You can use the tabIndex property and set it to -1 for all elements that you don't want to cycle through the tab.

<input type="text" id="no-tab-cycle" tabIndex="-1"/>

Off course you will need to manage this behavior through some smart selectors with jQuery or something, but depends how complex your forms are..

Maybe someone else has a better answer..

Update with sample

Using jQuery, and assuming your popup has an id of my-popup-dialog this code should do the trick, change the selectors as you see fit

$('input, textarea, select').each(function(index) {
    $(this).attr('tabIndex', '-1');
});

$('#my-popup-dialog input, #my-popup-dialog textarea, #my-popup-dialog select').each(function(index) {
    $(this).removeAttr('tabIndex');
});

There isn't a direct way to do this, but here's a (somewhat messy) way to do it. You basically need to keep track of which element currently has the focus:

  1. Handle the onfocus event for all controls on your page (you could set this up automatically) and in the handler make a note of the element which received focus, let's call this currentFocus .

  2. Similarly handle the onblur event and make a note of the element which just lost focus, let's call this previousFocus .

  3. Now add extra logic to the onfocus handler that does what you want: if previousFocus is the last control in your dialog and currentFocus is a control outside your dialog, set the focus to the first control in your dialog - this will handle tabbing out of the last control. Invert this logic to handle shift-tabbing out of the first control.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM