Is there a jQuery selector to get all elements that can get focus?

前端 未结 8 534
故里飘歌
故里飘歌 2020-12-01 15:54

This answer tells which HTML elements can receive focus. Is there a jQuery selector that matches exactly these elements?

For now I\'m just using $(\'input,sele

相关标签:
8条回答
  • 2020-12-01 16:27

    In jQuery not exists the selector you're finding.

    If you're already using jQueryUI, you can use :focusable selector.

    http://api.jqueryui.com/focusable-selector/

    0 讨论(0)
  • 2020-12-01 16:30

    Another simple, but complete, jQuery selector could be this one:

    $('a[href], area[href], input, select, textarea, button, iframe, object, embed, *[tabindex], *[contenteditable]')
    .not('[tabindex=-1], [disabled], :hidden')
    
    0 讨论(0)
  • 2020-12-01 16:32

    I have a relatively simple solution that returns all tabbable children, in their tab order, without using jQuery.

    function tabbable(el) {
        return [].map.call(el.querySelectorAll([
            'input',
            'select',
            'a[href]',
            'textarea',
            'button',
            '[tabindex]'
        ]), function(el, i) { return { el, i } }).
            filter(function(e) {
                return e.el.tabIndex >= 0 && !e.el.disabled && e.el.offsetParent; }).
            sort(function(a,b) {
                return a.el.tabIndex === b.el.tabIndex ? a.i - b.i : (a.el.tabIndex || 9E9) - (b.el.tabIndex || 9E9); });
    }
    

    For IE, consider implementing a different visibility check than e.el.offsetParent. jQuery can help you here.

    If you don't need the elements sorted, leave out the call to sort().

    0 讨论(0)
  • 2020-12-01 16:33

    You could check for elements that have the focus() function:

    $('*').each(function() {
      if(typeof this.focus == 'function') {
        // Do something with this element
      }
    }) ;
    

    Edit Thinking a little more, it would probably makes sense to have *:visible rather than just * as the selector for most applications of this.

    0 讨论(0)
  • 2020-12-01 16:34

    Instead of getting a list of focusable elements, you may want to try setting up a focus handler at the body element that captures focus events.

    $(document.body).on("focus", "*", function(e) {
        //Scroll to e.target
    });
    
    0 讨论(0)
  • 2020-12-01 16:37
    var allElementsThatCanBeFocused = $(':focusable');
    
    0 讨论(0)
提交回复
热议问题