This answer告诉哪些 HTML 元素可以接收焦点。是否有一个 jQuery 选择器能够完全匹配这些元素?
现在我只使用$('input,select,textarea,a')
,但我想知道是否有更精确的东西。
最佳答案
来自other SO answer referred to by the OP :
Today's browsers define focus() on HTMLElement, ...
因此,这意味着测试 focus
作为元素的成员无效,因为所有元素都会拥有它,无论它们是否真正接受焦点。
...but an element won't actually take focus unless it's one of:
- HTMLAnchorElement/HTMLAreaElement with an href
- 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- HTMLIFrameElement (though focusing it doesn't do anything useful). Other embedding elements also, maybe, I haven't tested them all.
- Any element with a
tabindex
那么,在 jQuery Selector 中明确命名所有这些怎么样? ?
$('a[href], area[href], input:not([disabled]), select:not([disabled]), textarea:not([disabled]), button:not([disabled]), iframe, object, embed, *[tabindex], *[contenteditable]')
<小时/>
更新#1:
我updated your jsFiddle here 。看起来有效。
我还添加了具有属性 contenteditable
的元素到上面的列表。
更新#2:
正如 @jfriend00 所指出的,“根据用途,人们可能想要过滤掉不可见的元素”。要实现此目的,只需应用 .filter(':visible')到从上面的选择器生成的集合。
<小时/>更新#3:
如Xavin pointed out :jQuery UI 现在有一个选择器,:focusable ,执行此功能。如果您已经在使用 jQuery UI,这可能是正确的选择。如果没有,那么您可能需要check out how jQuery UI does it 。无论如何,jQuery UI 页面上的描述为 :focusable
有帮助:
block 引用>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. area elements are focusable if they are inside a named map, have an href attribute, and there is a visible image using the map. All other elements are focusable based solely on their tabindex attribute and visibility.
因此,我上面提出的选择器很接近,但它未能考虑到一些细微差别。
这是从 jQuery UI 中摘取的函数,并进行了一些细微的修改以使其独立。 (这些调整未经测试,但应该有效):
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; } }
注意:上述功能仍然依赖于 jQuery,但不需要 jQuery UI。
关于javascript - 是否有一个 jQuery 选择器来获取所有可以获得焦点的元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7668525/