Focus Next Element In Tab Index

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

    I checked above solutions and found them quite lengthy. It can be accomplished with just one line of code:

    currentElement.nextElementSibling.focus();
    

    or

    currentElement.previousElementSibling.focus();
    

    here currentElement may be any i.e. document.activeElement or this if current element is in function's context.

    I tracked tab and shift-tab events with keydown event

    let cursorDirection = ''
    $(document).keydown(function (e) {
        let key = e.which || e.keyCode;
        if (e.shiftKey) {
            //does not matter if user has pressed tab key or not.
            //If it matters for you then compare it with 9
            cursorDirection = 'prev';
        }
        else if (key == 9) {
            //if tab key is pressed then move next.
            cursorDirection = 'next';
        }
        else {
            cursorDirection == '';
        }
    });
    

    once you have cursor direction then you can use nextElementSibling.focus or previousElementSibling.focus methods

提交回复
热议问题