Luc*_*emy 19 html javascript jquery tabindex
所以,例如,这是一个脚本:
<!-- Random content above this comment -->
<input type="text" tabindex="1" />
<input type="text" tabindex="2" />
<input type="text" tabindex="3" />
<input type="text" tabindex="4" />
<input type="text" tabindex="5" />
<input type="text" tabindex="6" />
<!-- Nothing underneath this comment -->
Run Code Online (Sandbox Code Playgroud)
因此,当用户按Tab键并浏览六个文本框,到达最后一个然后按Tab键时,它将转到第一个注释上方的内容,对吧?那么,我该如何让它tabindex="1"再次开始呢?
Dmi*_*ich 23
不幸的是,没有javascript,你不能这样做.您可以在最后一个元素上按下TAB(并确保它不是SHIFT+ TAB)键,然后手动将焦点设置为处理程序内的第一个元素.但是,将此逻辑绑定到键盘事件(即特定输入方法)不是通用的,并且在使用时可能无效:
我建议采用一种更普遍的方法,这种方法与焦点的改变方式无关.
我们的想法是围绕您的表单元素(您想要创建" tabindex循环 "),其中包含特殊的"焦点保护"元素,这些元素也是可聚焦的(它们分配了tabindex).这是您修改过的HTML:
<p>Some sample <a href="#" tabindex="0">content</a> here...</p>
<p>Like, another <input type="text" value="input" /> element or a <button>button</button>...</p>
<!-- Random content above this comment -->
<!-- Special "focus guard" elements around your
if you manually set tabindex for your form elements, you should set tabindex for the focus guards as well -->
<div class="focusguard" id="focusguard-1" tabindex="1"></div>
<input id="firstInput" type="text" tabindex="2" class="autofocus" />
<input type="text" tabindex="3" />
<input type="text" tabindex="4" />
<input type="text" tabindex="5" />
<input type="text" tabindex="6" />
<input id="lastInput" type="text" tabindex="7" />
<!-- focus guard in the end of the form -->
<div class="focusguard" id="focusguard-2" tabindex="8"></div>
<!-- Nothing underneath this comment -->
Run Code Online (Sandbox Code Playgroud)
现在,您只需监听focus这些保护元素上的事件,并手动将焦点更改为适当的字段(为简单起见使用jQuery):
$('#focusguard-2').on('focus', function() {
// "last" focus guard got focus: set focus to the first field
$('#firstInput').focus();
});
$('#focusguard-1').on('focus', function() {
// "first" focus guard got focus: set focus to the last field
$('#lastInput').focus();
});
Run Code Online (Sandbox Code Playgroud)
如您所见,我还确保当焦点从第一个输入向后移动时(例如,第一个输入上的SHIFT+ TAB),我们会快速回到最后一个输入.实例
请注意,焦点防护也会分配一个tabindex值,以确保它们在输入字段之前/之后立即聚焦.如果您没有手动将tabindex设置为您的输入,则两个焦点防护装置都可以tabindex="0"分配.
当然,当动态生成表单时,您也可以在动态环境中完成所有工作.只需弄清楚你的可聚焦元素(不那么琐碎的任务)并用相同的聚焦防护装置环绕它们.
希望有所帮助,如果您有任何问题,请告诉我.
UPDATE
正如nbro指出的那样,如果TAB在页面加载之后命中一个,则上面的实现具有选择最后一个元素的不良影响(因为这将聚焦第一个可聚焦元素#focusguard-1,这将触发聚焦最后一个输入.为了减轻这一点,你可以指定您最初要关注的元素,并将其与另一小块JavaScript集中在一起:
$(function() { // can replace the onload function with any other even like showing of a dialog
$('.autofocus').focus();
})
Run Code Online (Sandbox Code Playgroud)
有了这个,只需autofocus在你想要的任何元素上设置类,它将专注于页面加载(或你听的任何其他事件).
在这里我的解决方案,你不需要任何其他元素.正如您所看到的,元素将在<form>元素内循环.
$('form').each(function(){
var list = $(this).find('*[tabindex]').sort(function(a,b){ return a.tabIndex < b.tabIndex ? -1 : 1; }),
first = list.first();
list.last().on('keydown', function(e){
if( e.keyCode === 9 ) {
first.focus();
return false;
}
});
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
28961 次 |
| 最近记录: |