在JavaScript中使用箭头键移动焦点 [英] Shift focus with arrow keys in JavaScript

查看:112
本文介绍了在JavaScript中使用箭头键移动焦点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to be able to navigate through all the focusable elements on my webpage with the arrow key. So when the down-key is pressed the focus should shift to the focusable element beneath the current focussed element. You get the idea for the other arrow keys, when there is not a focusable element to shift to, the focus should remain the same.

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

This is what I got so far:

$(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

});

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

the idea was to get all the focus-able elements and than pick select the one that is suited for the arrow and shift focus.

我无法使这段代码正常工作(它包含一个错误)而且我还没有完全确定它是否能正常工作。

I'm not able to get this code to work (it contains a error) and I'm not completly sure it will even work.

Thnx提前

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

: I guess I was a little vague. I do not only want to go left and right, but also up and down.

推荐答案

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

What I would do is much simpler. Just add a common class among the objects who should have this functionality (f.ex. "move") and use:

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

        }
        if (e.keyCode == 37) {      
            $(".move:focus").prev().focus();

        }
    }
);
​

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

此代码很多更简单并希望拥有您需要的所有功能。

This code is much simpler and hopefully has all the functionality you need.

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

Just make sure the controls are in the correct order or this won't work properly.

这篇关于在JavaScript中使用箭头键移动焦点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆