简体   繁体   中英

How to set tabIndex on keydown or keyup given the activeElement tabIndex?

$(document).on("keyup", function(e) {
    var code = e.which;
    var currentTabIndex = document.activeElement.tabIndex;
    if (code == 40) {
        alert(currentTabIndex);
        //set tabIndex to currentIndex + 1;
    } else if (code == 39) {
        alert(currentTabIndex);
        //set tabIndex to currentIndex + 1;
    }
    else if (code == 38) {
        alert(currentTabIndex);
        //set tabIndex to currentIndex - 1;
    }
    else if (code == 37) {
        alert(currentTabIndex);
        //set tabIndex to currentIndex - 1;
    }
});

see FIDDLE for demo.

You can use .filter() to select the element that has a desired tabIndex and then use .focus() like so:

$('*').filter(function() {
    return this.tabIndex == currentTabIndex + 1;
}).focus();

Set focus to any element and then press the down arrow in the following demo:

DEMO

UPDATE

And here is how you would prevent tabbing if the active element accepts text input and either the Left Arrow or Right Arrow is pressed. The following is the complete code :

$(document).on("keyup", function(e) {
    var code = e.which,
        elm = document.activeElement, //capture the current element for later
        currentTabIndex = elm.tabIndex,
        nextTabIndex = code == 40 || code == 39 ? currentTabIndex + 1 :
    code == 38 || code == 37 ? currentTabIndex - 1 : null, //calculate next tab index
        isHoriz = code == 39 || code == 37; //Left or right arrow pressed
    $('[tabindex]').filter(function() {
        if( !$(elm).is(':text,textarea') || !isHoriz ) { //Exclude left/right arrow for text inputs
            return this.tabIndex == nextTabIndex;
        }
    })
    .focus();
});

DEMO

I'd say just grab the element with the next or previous tabindex and call .focus() on it:

$("[tabindex='" + (currentTabIndex + 1) + "']").focus();

or

$("[tabindex='" + (currentTabIndex - 1) + "']").focus();

EDIT:

So you want to stop the function if ('key pressed' == 'left arrow' or 'right arrow') and 'input type' == 'text'? Then write an if statement doing that exact thing:

if ((code == 39 || code == 37) && $(e.target).attr('type') == "text") return;

Put this at the second line of the function.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM