仅在按Tab键时才能在两个textareas之间切换

通常,当用户访问网页并按下键盘上的TAB按钮时,选择从页面的开头开始从一个元素移动到另一个元素。

我正在寻找一种解决方案,通过按键盘上的TAB按钮在两个特定文本区域之间切换,在加载网页时首先关注第一个文本区域? 对于此TAB键按下事件,必须忽略页面上的所有其他元素。

我怎么能得到这个?

Thanx的帮助!

=更新=

我已成功使其在Firefox 12.0下运行。 IE和Chrome无法正常运行。 假设文本区域ID是#ICCID和#MSISDN,则Jquery看起来像这样:

  $(function() { $(document).ready(function() { $("#ICCID").focus(); }); var $inp = $('.cls'); $inp.bind('keydown', function(e) { var key = e.which; if (key == 9) { e.preventDefault(); var nxtIdx = $inp.index(this) + 1; $(".cls:eq(" + nxtIdx + ")").focus(); //Simulate Enter after TAB var textInput = $("#MSISDN").val(); var lines = textInput .split(/\r|\r\n|\n/); if (lines > 1) { $("#MSISDN").on("keypress", function(e) { if (e.keyCode == 9) { var input = $(this); var inputVal = input.val(); setTimeout(function() { input.val(inputVal.substring(0,inputVal.length) + "\n"); }, 1); } }); } } if (key == 9) { e.preventDefault(); var nxtIdx = $inp.index(this) - 1; $(".cls:eq(" + nxtIdx + ")").focus(); //Simulate Enter after TAB $("#ICCID").on("keypress", function(e) { if (e.keyCode == 9) { var input = $(this); var inputVal = input.val(); setTimeout(function() { input.val(inputVal.substring(0,inputVal.length) + "\n"); }, 1); } }); } }); });  

使用jQuery捕获keydown动作,确定哪个textarea具有焦点,然后使用focus()方法将焦点设置为另一个textarea。

假设你的textareas有id =“textarea1”和id =“textarea2”。 首先,您可以在页面加载时将焦点设置到第一个textarea: $('#textarea1').focus();

 $("body").keypress(function(e) { var code = (e.keyCode ? e.keyCode : e.which); switch(code) { case 9: if($("#textarea1").focus()){ //First one has focus, change to second one $("#textarea2").focus(); } else if($("#textarea2").focus()) { //Second one has focus, change to first one $("#textarea1").focus(); } } }); 

好的,我已经为我的任务找到了解决方案! 它还包括在TAB键事件之后模拟ENTER键,因此用户无需按ENTER键转到新行。 经过IE9,FF12,Chrome 18.0.x的测试

这里是:

     

那怎么样……我觉得在工作中无聊…

http://jsbin.com/uqalej/3/

HTML:

       

JS:

 var d = document, t1 = d.getElementById("t1"), t2 = d.getElementById("t2"), nodeType, nodeTypes = [], i, iLen, y, yLen; nodeTypes.push( d.getElementsByTagName("textarea") ); nodeTypes.push( d.getElementsByTagName("input") ); nodeTypes.push( d.getElementsByTagName("select") ); i = 0; iLen = nodeTypes.length; for ( ; i < iLen; i++ ) { nodeType = nodeTypes[i]; y = 0; yLen = nodeType.length; for ( ; y < yLen; y++ ) { if ( nodeType[y] != t1 && nodeType[y] != t2 ) { nodeType[y].onfocus = function() { if ( window.toggleBetween ) t1.focus(); }; } } } 

在页面加载时使用javascript:

 document.getElementById("textarea1").focus(); document.getElementById('textarea1').tabIndex="1"; document.getElementById('textarea2').tabIndex="2";