如何在给定activeElement tabIndex的keydown或keyup上设置tabIndex? [英] How to set tabIndex on keydown or keyup given the activeElement tabIndex?

查看:175
本文介绍了如何在给定activeElement tabIndex的keydown或keyup上设置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;
    }
});

参见 FIDDLE 用于演示。

推荐答案

您可以使用 .filter()选择具有所需 tabIndex 的元素,然后使用 .focus(),如下所示:

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

更新

以下是您要预防的方法 tabbing 如果活动元素接受文本输入,并且按下了左箭头右箭头以下是完整代码

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

这篇关于如何在给定activeElement tabIndex的keydown或keyup上设置tabIndex?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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