16

我有一个巨大的输入表单和字段供用户输入。

在用户使用 tab 键移动到下一个字段的表单中,在使用 javascript 禁用 tab 键的中间有一些隐藏字段和只读文本框。

现在用户发现很难使用 Tab 键,并且希望在键盘的向下箭头键上具有相同的功能。

我正在使用下面的代码来调用 js 上的 tab 键代码但不工作,请一些人帮助我。

function handleKeyDownEvent(eventRef)
{ 
 var charCode = (window.event) ? eventRef.keyCode : eventRef.which;

 //alert(charCode);

 // Arrow keys (37:left, 38:up, 39:right, 40:down)...
 if (  (charCode == 40) )
 {

  if ( window.event )
   window.event.keyCode = 9;
  else
   event.which = 9;

  return false;
 }

 return true;
}

<input type="text"   onkeydown=" return  handleKeyDownEvent(event);" >
4

3 回答 3

12

Using jQuery, you can do this :

$('input, select').keydown(function(e) {
    if (e.keyCode==40) {
        $(this).next('input, select').focus();
    }
});

When you press the down arrow key (keyCode 40), the next input receives the focus.

DEMO​</p>

EDIT :

In Vanilla JS, this could be done like this :

function doThing(inputs) {    
    for (var i=0; i<inputs.length; i++) {
        inputs[i].onkeydown = function(e) {
            if (e.keyCode==40) {
                var node = this.nextSibling;
                while (node) {
                    console.log(node.tagName);
                    if (node.tagName=='INPUT' || node.tagName=='SELECT') {
                        node.focus();
                        break;
                    }
                    node = node.nextSibling;                
                }
            }
        };
    };
}
doThing(document.getElementsByTagName('input'));
doThing(document.getElementsByTagName('select'));

Note that you'd probably want to map the up key too, and go to first input at last one, etc. I let you handle the details depending on your exact requirements.

于 2012-09-13T13:16:53.910 回答
4

这是我的最终工作代码:

$('input[type="text"],textarea').keydown( function(e) {
    var key = e.charCode ? e.charCode : e.keyCode ? e.keyCode : 0;

    if(key == 40) {
        e.preventDefault();
        var inputs = $(this).parents('form').find(':input[type="text"]:enabled:visible:not("disabled"),textarea');

        inputs.eq( inputs.index(this)+ 1 ).focus();
        inputs.eq( inputs.index(this)+ 1 ).click();
    }
});
于 2012-09-18T10:42:31.593 回答
0

If I understand correctly, some fields are read-only, so the tab key still activates them, even though they are read-only, and this is annoying, as you have to press the tab key perhaps several times to get to the next editable field. If that is correct, then an alternate solution would be to use the tabindex attribute on your input fields, indexing each one so that the read-only and otherwise non-editable fields aren't selected. You can find more info on the tabindex attribute here.

于 2012-09-13T13:17:13.307 回答