Situation:
I have a webpage which opens modal windows (light boxes) which contain forms where the user can input data. Users generally navigate using the keyboard, tabbing from one field to the next.
Problem:
When a modal window opens, only the window is active, the rest of the page is not accessible using the mouse, but elements can be reached by tabbing out of the modal window.
Question:
How can I restrict movement by using the tab button to only the elements within the form window?
The only thing I can think of is using Javascript to set tabindex=-1
on all form elements (and other focusable elements) when the modal window is opened and then set the tabindex
values back to their previous values when the modal window is closed.
Is there a simpler/better way?
How about catching the tab-key
? On the last element and then put the focus on the first and vice versa with shift-tab
This I am using in a multi-modless-diaolog environment, to keep the focus with in a Dialog, switching between dialogs with mouse or other key
inputs=".editing, input, textarea, button, a, select"
no_tab="[type='hidden'], :disabled"
$focusable=dlg.$form.find(inputs).not(no_tab)
$fa_first=$focusable.first()
$fa_last=$focusable.last()
$fa_last.on("keydown", (evt) =>
if evt.keyCode==9 && ! evt.shiftKey
$fa_first.focus()
evt.preventDefault()
false
)
$fa_first.on("keydown", (evt) =>
if evt.keyCode==9 && evt.shiftKey
$fa_last.focus()
evt.preventDefault()
false
)
small edit: replaced my on "unibind()" (=.off(x).on(x)) function through jQuery "on()"
Have a look at the jQuery BlockUI Plugin. They have an example using a modal box with two buttons, and it restricts tabbing as well.
It may or may not work out-of-the-box with your modal windows, but it's worth a look instead of having to implement your own work-around.
in case you want to restrict the focus inside dom "parent"
parent.addEventListener('focusout', function(event) {
event.stopPropagation();
if (node.contains(event.relatedTarget)) { // if focus moved to another
parent descend
return;
}
parent.focus(); // otherwise focus on parent or change to another dom
})
supported by all mordern browsers
Even though it is an old post I was looking for a solution to this problem and did the following to solve it.
Using JQuery I disabled all input fields in different forms and divs as soon as the modal window opens up (except the ones on the modal form itself).
$('#formId :input').prop('disabled',true);
when the modal form is closed, you can enable the input elements again.
Disabled fields are not considered when "tabbing" around your page.
来源:https://stackoverflow.com/questions/5206813/restrict-tabindex-focusing-to-a-section-of-the-page