我有一个弹出式div,里面有很多控件。如果我连续按tab键,焦点不能离开div到父表单。如何实现这个功能? 谢谢。
在普通的HTML中无法强制执行此操作。
然而,有很多脚本可以为您处理这个问题。我强烈建议使用其中之一,因为有很多需要解决的问题(下拉菜单可能会出现在模态div前面)。
如果您正在使用asp.net,您可以查看具有模态弹出对话框的ajax控件工具包。
几乎每个体面的JavaScript框架都有插件来完成这个任务。我碰巧经常使用jQuery,它有许多插件来处理这个问题:
如果你需要自己制作一个,这里是一个使用jQuery的教程: http://www.queness.com/post/77/simple-jquery-modal-window-tutorial
祝你好运,找到最适合你的解决方案!
我基于这篇帖子中的知识和答案编写了一个迷你框架。
它使用了JQuery UI。
欢迎提出改进意见。
以下是框架对象:
var TabLim = {};
TabLim.activate = function(el) {
TabLim.deactivate();
TabLim._el = el;
$(window).on('keydown', TabLim._handleTab);
return TabLim;
};
TabLim.deactivate = function() {
TabLim._el = null;
// detach old focus events
TabLim._detachFocusHandlers();
TabLim._els = null;
TabLim._currEl = null;
$(window).off('keydown', TabLim._handleTab);
return TabLim;
};
TabLim.setFocus = function(prev) {
// detach old focus events
TabLim._detachFocusHandlers();
// scan for new tabbable elements
var tabbables = TabLim._el.find(':tabbable');
TabLim._els = [];
// wrap elements in jquery
for ( var i = 0; i < tabbables.length; i++) {
var el = $(tabbables[i]);
// set focus listener on each element
el.on('focusin', TabLim._focusHandler);
TabLim._els.push(el);
}
// determine the index of focused element so we will know who is
// next/previous to be focused
var currIdx = 0;
for ( var i = 0; i < TabLim._els.length; i++) {
var el = TabLim._els[i];
// if focus is set already on some element
if (TabLim._currEl) {
if (TabLim._currEl === el[0]) {
currIdx = i;
prev ? currIdx-- : currIdx++;
break;
}
} else {
// focus is not set yet.
// let's set it by attribute "autofocus".
if (el.attr('autofocus') !== undefined) {
currIdx = i;
break;
}
}
}
if (currIdx < 0) {
currIdx += TabLim._els.length;
}
if (TabLim._els.length) {
TabLim._els[Math.abs(currIdx % TabLim._els.length)].focus();
}
return TabLim;
};
TabLim._handleTab = function(e) {
if (e.which === 9) {
e.preventDefault();
TabLim.setFocus(e.shiftKey);
}
};
TabLim._focusHandler = function(e) {
TabLim._currEl = e.currentTarget;
};
TabLim._detachFocusHandlers = function() {
if (TabLim._els) {
for ( var i = 0; i < TabLim._els.length; i++) {
TabLim._els[i].off('focusin', TabLim._focusHandler);
}
}
};
TabLim.activate($('.yourDic')).setFocus();
2) 停用
TabLim.deactivate();