Focus Next Element In Tab Index

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

    Here's something I build for this purpose:

    focusNextElement: function () {
        //add all elements we want to include in our selection
        var focussableElements = 'a:not([disabled]), button:not([disabled]), input[type=text]:not([disabled]), [tabindex]:not([disabled]):not([tabindex="-1"])';
        if (document.activeElement && document.activeElement.form) {
            var focussable = Array.prototype.filter.call(document.activeElement.form.querySelectorAll(focussableElements),
            function (element) {
                //check for visibility while always include the current activeElement 
                return element.offsetWidth > 0 || element.offsetHeight > 0 || element === document.activeElement
            });
            var index = focussable.indexOf(document.activeElement);
            if(index > -1) {
               var nextElement = focussable[index + 1] || focussable[0];
               nextElement.focus();
            }                    
        }
    }
    

    Features:

    • configurable set of focusable elements
    • no jQuery needed
    • works in all modern browsers
    • fast & lightweight

提交回复
热议问题