简体   繁体   English

是否有一个 jQuery 选择器来获取所有可以获得焦点的元素?

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

This answer tells which HTML elements can receive focus. 这个答案告诉了哪些 HTML 元素可以接收焦点。 Is there a jQuery selector that matches exactly these elements?是否有与这些元素完全匹配的 jQuery 选择器?

For now I'm just using $('input,select,textarea,a') , but I wonder if there's something more precise.现在我只是使用$('input,select,textarea,a') ,但我想知道是否有更精确的东西。

From the other SO answer referred to by the OP :OP 提到其他 SO 答案中

Today's browsers define focus() on HTMLElement, ...今天的浏览器在 HTMLElement 上定义了 focus(),...

So, this means testing for focus as a member of the element is not effective, because all elements will have it, regardless of whether they actually accept focus or not.所以,这种检测手段对focus为元素的成员是无效的,因为所有元素都会有它,无论他们是否真正接受焦点。

...but an element won't actually take focus unless it's one of: ...但一个元素实际上不会成为焦点,除非它是以下之一:

  • HTMLAnchorElement/HTMLAreaElement with an href带有 href 的 HTMLAnchorElement/HTMLAreaElement
  • HTMLInputElement/HTMLSelectElement/HTMLTextAreaElement/HTMLButtonElement but not with disabled (IE actually gives you an error if you try), and file uploads have unusual behaviour for security reasons HTMLInputElement/HTMLSelectElement/HTMLTextAreaElement/HTMLButtonElement 但没有disabled (如果你尝试,IE 实际上会给你一个错误),并且出于安全原因,文件上传有异常行为
  • HTMLIFrameElement (though focusing it doesn't do anything useful). HTMLIFrameElement (虽然聚焦它并没有做任何有用的事情)。 Other embedding elements also, maybe, I haven't tested them all.其他嵌入元素也可能,我还没有全部测试过。
  • Any element with a tabindex任何带有tabindex元素

So, what about naming all those explicitly in a jQuery Selector ?那么,如何在jQuery Selector 中明确命名所有这些呢?

$('a[href], area[href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), button:not([disabled]), iframe, object, embed, *[tabindex], *[contenteditable]')

Update #1 :更新#1

I updated your jsFiddle here .在这里更新了你的 jsFiddle It appears to work.它似乎有效。

I also added elements with attribute contenteditable to the list above.我还在上面的列表中添加了具有contenteditable属性的元素。


Update #2 :更新#2

As @jfriend00 pointed out, "Depending upon the use, one may want to filter out elements that aren't visible".正如@jfriend00 指出的那样,“根据使用情况,人们可能希望过滤掉不可见的元素”。 To accomplish this, simply apply .filter(':visible') to the set generated from the above selector.要实现这一点,只需将.filter(':visible')应用于从上述选择器生成的集合。


Update #3 :更新 #3

As Xavin pointed out : jQuery UI now has a selector, :focusable , that performs this function.正如Xavin 指出的那样:jQuery UI 现在有一个选择器, :focusable ,可以执行此功能。 If you're already using jQuery UI, this might be the way to go.如果您已经在使用 jQuery UI,那么这可能是您要走的路。 If not, then you might want to check out how jQuery UI does it .如果没有,那么您可能想看看 jQuery UI 是如何做到的 In any case, the description on jQuery UI's page for :focusable is helpful:无论如何,jQuery UI 页面上关于:focusable的描述很有帮助:

Elements of the following type are focusable if they are not disabled: input, select, textarea, button, and object.如果未禁用以下类型的元素,则它们是可聚焦的:输入、选择、文本区域、按钮和对象。 Anchors are focusable if they have an href or tabindex attribute.如果锚具有 href 或 tabindex 属性,则它们是可聚焦的。 area elements are focusable if they are inside a named map, have an href attribute, and there is a visible image using the map.如果 area 元素位于命名地图内、具有 href 属性并且有使用地图的可见图像,则它们是可聚焦的。 All other elements are focusable based solely on their tabindex attribute and visibility.所有其他元素都可以仅根据它们的 tabindex 属性和可见性来聚焦。

So, the selector I proposed above is close, but it fails to account for a few nuances.所以,我上面提出的选择器很接近,但它没有考虑到一些细微差别。

Here's the function ripped from jQuery UI, with minor adaptations to make it self-contained.这是从 jQuery UI 中提取的函数,并进行了微小的调整以使其独立。 (the adaptations are untested, but should work): (改编未经测试,但应该有效):

function focusable( element ) {
    var map, mapName, img,
        nodeName = element.nodeName.toLowerCase(),
        isTabIndexNotNaN = !isNaN( $.attr( element, "tabindex" ) );
    if ( "area" === nodeName ) {
        map = element.parentNode;
        mapName = map.name;
        if ( !element.href || !mapName || map.nodeName.toLowerCase() !== "map" ) {
            return false;
        }
        img = $( "img[usemap=#" + mapName + "]" )[0];
        return !!img && visible( img );
    }
    return ( /input|select|textarea|button|object/.test( nodeName ) ?
        !element.disabled :
        "a" === nodeName ?
            element.href || isTabIndexNotNaN :
            isTabIndexNotNaN) &&
        // the element and all of its ancestors must be visible
        visible( element );

    function visible( element ) {
      return $.expr.filters.visible( element ) &&
        !$( element ).parents().addBack().filter(function() {
          return $.css( this, "visibility" ) === "hidden";
        }).length;
    }
}

Note: the above function still depends on jQuery, but should not require jQuery UI.注意:上述函数仍然依赖于 jQuery,但应该不需要 jQuery UI。

Another simple, but complete, jQuery selector could be this one:另一个简单但完整的 jQuery 选择器可能是这样的:

$('a[href], area[href], input, select, textarea, button, iframe, object, embed, *[tabindex], *[contenteditable]')
.not('[tabindex=-1], [disabled], :hidden')

You could check for elements that have the focus() function:您可以检查具有focus()函数的元素:

$('*').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.再想一想,将*:visible而不仅仅是*作为大多数应用程序的选择器可能更有意义。

I have a relatively simple solution that returns all tabbable children, in their tab order, without using jQuery.我有一个相对简单的解决方案,它在不使用 jQuery 的情况下,按 Tab 键顺序返回所有可制表的子项。

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 .对于 IE,请考虑实施与e.el.offsetParent不同的可见性检查。 jQuery can help you here. jQuery 可以在这里为您提供帮助。

If you don't need the elements sorted, leave out the call to sort() .如果您不需要对元素进行排序,请省略对sort()的调用。

In jQuery not exists the selector you're finding.在 jQuery 中不存在您正在查找的选择器。

If you're already using jQueryUI, you can use :focusable selector.如果您已经在使用 jQueryUI,则可以使用: focusable 选择器。

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

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.您可能想要尝试在捕获焦点事件的body元素上设置一个焦点处理程序,而不是获取可聚焦元素的列表。

$(document.body).on("focus", "*", function(e) {
    //Scroll to e.target
});
var allElementsThatCanBeFocused = $(':focusable');

A general test to know whether an element supports a particular type of listener is to see if it has a related property, eg to test for support for the focus event, use:了解元素是否支持特定类型侦听器的一般测试是查看它是否具有相关属性,例如测试是否支持焦点事件,请使用:

if ('focus' in element) {
  // element supports the focus event
}

However, there are some exceptions.但是,也有一些例外。 See the answers to How do you programmatically determine to which events an HTML object can listen for?请参阅如何以编程方式确定 HTML 对象可以侦听哪些事件的答案 . .

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM