Find next closest focusable element using jquery? [closed]

孤者浪人 提交于 2019-12-01 15:26:46

I've already done that before. Try my solution here http://jsfiddle.net/R8PhF/3/

$(document).ready(function(){
    $('#mytextbox').keyup(function(e){
        var code = (e.keyCode ? e.keyCode : e.which);
        if(code == 13) {
            var tabables = $("*[tabindex != '-1']:visible");
            var index = tabables.index(this);
            tabables.eq(index + 1).focus();
        }        
    });
});​

By the way, this is a legitimate technical question and could very well be a business requirement. I have been asked to build such behavior into back office apps quite offten. There are many native apps that behave this way.

I addressed this requirement by building my form using DIVs with contenteditable=true like the example below.

<html>
<head>
  <style type="text/css">

    div.input { border:1px solid #aaa; width:300px; }

  </style>

</head>
<body>

    <div contenteditable="true" class="input"><strong>explore the world,</strong> e.g. paris, france</div>

</body>
</html>

You can the capture the key event for ENTER and simply set focus on the next sibling using JQuery.

Let me know if you need further clarification.

Hope this helps. Good Luck.

Algorithm-wise:

  1. Keep a list of all elements that can be focussed. Do not rely on the DOM for this. You must keep the list yourself. If you don't know which elements are on the page you've already done something wrong. The DOM is a view not a datastore, treat it accordingly. Many novices who use jQuery make this mistake, and with jQuery this mistake is easy to make.

  2. Find the position of all focussable elements on the page. In accordance with 1. the best way is of course to know the relative position of all elements even without looking at the DOM. With jQuery you can use .dimension(). You may have to do some bookkeeping to keep this list up to date (ie. when your data/view changes).

  3. Find the position of the current focussed element.

  4. Use some algorithm to compare it to your list of other positions and get the closest (this can mean a lot of things, you probably know what you want).

  5. Then set the focus to the element.

There are many choices you can make here, some depend on performance others depend on interaction and interface design.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!