简体   繁体   English

Javascript:陷阱焦点在对话框中

[英]Javascript: trap focus in dialog

I have a popup dialog (a div with a high z-index) which contains some input elements. 我有一个弹出对话框(一个高z-index的div),它包含一些输入元素。 While this dialog is open, I'd like tab and shift-tab to only cycle between elements in this dialog. 当这个对话框打开时,我希望tab和shift-tab只在这个对话框中的元素之间循环。 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. 您可以使用tabIndex属性并将其设置为-1,以表示您不想在选项卡中循环的所有元素。

<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.. 当然,您需要通过一些使用jQuery或其他东西的智能选择器来管理这种行为,但取决于您的表单有多复杂。

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 使用jQuery,并假设你的弹出窗口具有my-popup-dialog的id,这段代码应该可以解决问题,根据你的需要更改选择器

$('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 . 处理页面上所有控件的onfocus事件(您可以自动设置)并在处理程序中记下接收焦点的元素,让我们调用此currentFocus

  2. Similarly handle the onblur event and make a note of the element which just lost focus, let's call this previousFocus . 类似地处理onblur事件并记下刚失去焦点的元素,让我们调用这个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. 现在为执行所需操作的onfocus处理程序添加额外的逻辑:如果previousFocus是对话框中的最后一个控件而currentFocus是对话框外的控件,则将焦点设置为对话框中的第一个控件 - 这将处理标签最后一个控制 Invert this logic to handle shift-tabbing out of the first control. 反转此逻辑以处理第一个控件中的shift-tabbing。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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