模拟TAB keydown:聚焦由'tabIndex`确定的下一个元素

时间:2011-09-05 02:53:45

标签: jquery

我有两个输入元素,第一个是聚焦的,我想通过模拟TAB keypress / keydown事件来关注第二个。 (注意:我不想使用.next()等。)

这是我的代码,灵感来自this question

$('input').first().focus();

var e = $.Event('keydown');

e.which = 9; // TAB
$(':focus').trigger(e);

请参阅http://jsfiddle.net/3PcPH/

代码不起作用。有什么问题?

5 个答案:

答案 0 :(得分:35)

使用Javascript没有简单的编程方式来做到这一点......所以这是一种蛮力的方式。

According to W3

  

可能会获得焦点的元素应由用户代理导航   根据以下规则:

     
      
  1. 支持tabindex属性并指定一个的元素   首先导航它的正值。导航从   具有最低tabindex值的元素到具有最高元素的元素   值。价值观不必是连续的,也不必以任何方式开始   特别的价值。具有相同tabindex值的元素应该   按照它们在字符流中出现的顺序进行导航。
  2.   
  3. 那些   不支持tabindex属性或支持它的元素   为其分配值“0”接下来导航。这些元素是   按照它们在字符流中出现的顺序导航。
  4.   
  5. 元素   被禁用的人不参与Tab键顺序。
  6.   

我通过在其tabIndex顺序中以tabIndex > 0形式存储元素的顺序,然后按照它们在文档中出现的顺序连接其余元素来完成此操作。下面的代码模拟了一个tab键,当你专注于表单输入并按下字母'z'时(但你可以将它改为你需要的任何条件):

$(':input').keypress(function(e){ 

    // if 'z' pressed
    if (e.which == 122) {

        // if we haven't stored the tabbing order
        if (!this.form.tabOrder) {

            var els = this.form.elements,
                ti = [],
                rest = [];

            // store all focusable form elements with tabIndex > 0
            for (var i = 0, il = els.length; i < il; i++) {
                if (els[i].tabIndex > 0 &&
                    !els[i].disabled && 
                    !els[i].hidden && 
                    !els[i].readOnly &&
                    els[i].type !== 'hidden') {
                    ti.push(els[i]);
                }
            }

            // sort them by tabIndex order
            ti.sort(function(a,b){ return a.tabIndex - b.tabIndex; });

            // store the rest of the elements in order
            for (i = 0, il = els.length; i < il; i++) {
                if (els[i].tabIndex == 0 &&
                    !els[i].disabled && 
                    !els[i].hidden && 
                    !els[i].readOnly &&
                    els[i].type !== 'hidden') {
                    rest.push(els[i]);
                }
            }

            // store the full tabbing order
            this.form.tabOrder = ti.concat(rest);
        }

        // find the next element in the tabbing order and focus it
        // if the last element of the form then blur
        // (this can be changed to focus the next <form> if any)
        for (var j = 0, jl = this.form.tabOrder.length; j < jl; j++) {
            if (this === this.form.tabOrder[j]) {
                if (j+1 < jl) {
                    $(this.form.tabOrder[j+1]).focus();
                } else {
                    $(this).blur();
                }
            }
        }

    }

});

See demo

答案 1 :(得分:4)

默认的标签行为是转到下一个(按源顺序排列)表单元素,这样您就可以遍历所关注的所有元素,找到具有焦点的元素,并将焦点移动到下一个元素。我们有:input选择器来查找表单元素,如下所示:

var $all = $('form :input');
var focused = $(':focus')[0];
for(var i = 0; i < $all.length - 1; ++i) {
    if($all[i] != focused)
        continue;
    $all[i + 1].focus();
    break;
}
// Must have been focused on the last one or none of them.
if(i == $all.length - 1)
    $all[0].focus();

演示:http://jsfiddle.net/ambiguous/Avugy/1/

或者您可以设置tabindex属性并使用环绕增加它们:

var next_idx = parseInt($(':focus').attr('tabindex'), 10) + 1;
var $next_input = $('form [tabindex=' + next_idx + ']');
if($next_input.length)
    $next_input.focus();
else
    $('form [tabindex]:first').focus();

演示:http://jsfiddle.net/ambiguous/k9VpV/

处理tabindex属性值中的间隙作为练习。

答案 2 :(得分:0)

答案 3 :(得分:0)

这是一个使用jquery使用Enter键模拟TAB功能的解决方案:

https://jsfiddle.net/tuho879j/

$('input').keypress(function(event){
  if(event.which == '13')   //ENTER     
  {
    var tabIndex = $(this).attr('tabIndex');

    var all_inputs = $(this).closest('table').find('input:visible');
    var inputs = all_inputs.filter(function() {
      return $(this).attr("tabIndex") > tabIndex;
    })

    if(inputs.length != 0)
    {
        inputs = $(inputs).sort(function(a,b){
          return $(a).attr('tabIndex')-$(b).attr('tabIndex');
        });
    }
    else
    {
        inputs = $(all_inputs).sort(function(a,b){
          return $(a).attr('tabIndex')-$(b).attr('tabIndex');
        });
    }


    var elem = inputs.eq( inputs.index(this)+ 1 );
    if(elem.length == 0)
        elem = inputs.eq(0);

    elem.focus();
    event.preventDefault();
  }
});

答案 4 :(得分:-1)

$('input').first().focus();

var e = $.Event('keydown');

e.which = 9; // TAB
$(':focus').bind('keydown',function(e){
    if(e.which == 9){
        //this.value="tab";
        $('input:eq(1)').focus();
    }
   e.preventDefault(); 
});

您需要将'keydown'事件绑定到并自定义您的事件函数。

相关问题