Focus Next Element In Tab Index

后端 未结 20 2186
失恋的感觉
失恋的感觉 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:33

    I've never implemented this, but I've looked into a similar problem, and here's what I would try.

    Try this first

    First, I would see if you could simply fire a keypress event for the Tab key on the element that currently has focus. There may be a different way of doing this for different browsers.

    If that doesn't work, you'll have to work harder…

    Referencing the jQuery implementation, you must:

    1. Listen for Tab and Shift+Tab
    2. Know which elements are tab-able
    3. Understand how tab order works

    1. Listen for Tab and Shift+Tab

    Listening for Tab and Shift+Tab are probably well-covered elsewhere on the web, so I'll skip that part.

    2. Know which elements are tab-able

    Knowing which elements are tab-able is trickier. Basically, an element is tab-able if it is focusable and does not have the attribute tabindex="-1" set. So then we must ask which elements are focusable. The following elements are focusable:

    • input, select, textarea, button, and object elements that aren't disabled.
    • a and area elements that have an href or have a numerical value for tabindex set.
    • any element that has a numerical value for tabindex set.

    Furthermore, an element is focusable only if:

    • None of its ancestors are display: none.
    • The computed value of visibility is visible. This means that the nearest ancestor to have visibility set must have a value of visible. If no ancestor has visibility set, then the computed value is visible.

    More details are in another Stack Overflow answer.

    3. Understand how tab order works

    The tab order of elements in a document is controlled by the tabindex attribute. If no value is set, the tabindex is effectively 0.

    The tabindex order for the document is: 1, 2, 3, …, 0.

    Initially, when the body element (or no element) has focus, the first element in the tab order is the lowest non-zero tabindex. If multiple elements have the same tabindex, you then go in document order until you reach the last element with that tabindex. Then you move to the next lowest tabindex and the process continues. Finally, finish with those elements with a zero (or empty) tabindex.

提交回复
热议问题