Focus Next Element In Tab Index

后端 未结 20 2101
失恋的感觉
失恋的感觉 2020-11-27 03:06

I am trying to move the focus to the next element in the tab sequence based upon the current element which has focus. Thus far I have not turned up anything in my searches.<

20条回答
  •  清酒与你
    2020-11-27 03:25

    It seems that you can check the tabIndex property of an element to determine if it is focusable. An element that is not focusable has a tabindex of "-1".

    Then you just need to know the rules for tab stops:

    • tabIndex="1" has the highest priorty.
    • tabIndex="2" has the next highest priority.
    • tabIndex="3" is next, and so on.
    • tabIndex="0" (or tabbable by default) has the lowest priority.
    • tabIndex="-1" (or not tabbable by default) does not act as a tab stop.
    • For two elements that have the same tabIndex, the one that appears first in the DOM has the higher priority.

    Here is an example of how to build the list of tab stops, in sequence, using pure Javascript:

    function getTabStops(o, a, el) {
        // Check if this element is a tab stop
        if (el.tabIndex > 0) {
            if (o[el.tabIndex]) {
                o[el.tabIndex].push(el);
            } else {
                o[el.tabIndex] = [el];
            }
        } else if (el.tabIndex === 0) {
            // Tab index "0" comes last so we accumulate it seperately
            a.push(el);
        }
        // Check if children are tab stops
        for (var i = 0, l = el.children.length; i < l; i++) {
            getTabStops(o, a, el.children[i]);
        }
    }
    
    var o = [],
        a = [],
        stops = [],
        active = document.activeElement;
    
    getTabStops(o, a, document.body);
    
    // Use simple loops for maximum browser support
    for (var i = 0, l = o.length; i < l; i++) {
        if (o[i]) {
            for (var j = 0, m = o[i].length; j < m; j++) {
                stops.push(o[i][j]);
            }
        }
    }
    for (var i = 0, l = a.length; i < l; i++) {
        stops.push(a[i]);
    }
    

    We first walk the DOM, collecting up all tab stops in sequence with their index. We then assemble the final list. Notice that we add the items with tabIndex="0" at the very end of the list, after the items with a tabIndex of 1, 2, 3, etc.

    For a fully working example, where you can tab around using the "enter" key, check out this fiddle.

提交回复
热议问题