在JavaScript中使用箭头键移动焦点

我希望能够使用箭头键浏览网页上的所有可聚焦元素。 因此,当按下向下键时,焦点应移动到当前聚焦元素下方的可聚焦元素。 你可以得到其他箭头键的想法,当没有可转移的可聚焦元素时,焦点应该保持不变。

这是我到目前为止所得到的:

$(document).keydown(function(e){ if (e.keyCode == 37) { //left var offset = $("*:focus").offset(); var allElements = $("#container").find('a[href], area[href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), button:not([disabled]), iframe, object, embed, *[tabindex], *[contenteditable]'); var arr = jQuery.makeArray(allElements); var topLeft = offset.left var minus = topLeft; var currentElement = $("*:focus"); for(var i = 0; i < arr.length; i++) { if ( (arr[i].offset().left < offset.left) // This doesn't work for some reason && ((offset.left - arr[i].offset().left) < minus)) { currentElement = arr[i]; minus = offset.left - arr[i].offset().left; topLeft = arr[i].offset().left; } currentElement.focus(); } alert( "left pressed" ); return false; } // Other Keys 

});

我们的想法是获得所有可聚焦元素,然后选择适合箭头和移位焦点的元素。

我无法使这个代码工作(它包含一个错误),我不完全确定它甚至可以工作。

Thnx提前

[编辑]:我想我有点模糊。 我不仅想要左右移动,而且还要上下移动。

我会做的更简单。 只需在应具有此function的对象中添加一个公共类(f.ex。“move”)并使用:

 $(document).keydown( function(e) { if (e.keyCode == 39) { $(".move:focus").next().focus(); } if (e.keyCode == 37) { $(".move:focus").prev().focus(); } } );​ 

参见示例: http : //jsfiddle.net/uJ4PJ/

此代码简单,并且希望具有您需要的所有function。

只需确保控件的顺序正确,否则无法正常工作。

预览 – http://jsfiddle.net/FehKh/ ;)

HTML:

 jajaj jajasdaaj jajaacasj  

JS:

 // init $('.focused').focus(); // actual code $(document).keydown(function(e){ if (e.keyCode == 37) { // left if($('.focused').prev('.focusable').length) $('.focused').removeClass('focused').prev('.focusable').focus().addClass('focused'); } if (e.keyCode == 39) { // right if($('.focused').next('.focusable').length) $('.focused').removeClass('focused').next('.focusable').focus().addClass('focused'); } });​ 

经过多次试验和错误,我开发了以下代码:

 function navigate(origin, sens) { var inputs = $('#form').find('input:enabled'); var index = inputs.index(origin); index += sens; if (index < 0) { index = inputs.length - 1; } if (index > inputs.length - 1) { index = 0; } inputs.eq(index).focus(); } $('input').keydown(function(e) { if (e.keyCode==37) { navigate(e.target, -1); } if (e.keyCode==39) { navigate(e.target, 1); } }); 

右箭头作为选项卡

左箭头作为class次选项卡

通过检查一些文章并在流链接上堆叠来实现

 jQuery.fn.elementAfter = function(other) { for(i = 0; i < this.length - 1; i++) { if (this[i] == other) { return jQuery(this[i + 1]); } } return jQuery; } ; jQuery.fn.elementBefore = function(other) { if (this.length > 0) { for(i = 1; i < this.length; i++) { if (this[i] == other) { return jQuery(this[i - 1]); } } } return jQuery; }; 

https://jsfiddle.net/bkLnq5js/79/