javascript 如何检查 dom 元素是否可聚焦?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18261595/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-27 11:15:15  来源:igfitidea点击:

How to check if a dom element is focusable?

javascriptjquerydom

提问by Konstantin Solomatov

Many DOM elements are focusable: divs with tabIndex, input elements, etc. Is there any simple way to check whether an element is focusable than checking a zillion of different cases? Is there a jQuery method for this?

许多 DOM 元素是可聚焦的:带有 tabIndex、输入元素等的 div。有没有比检查无数种不同情况更简单的方法来检查元素是否可聚焦?是否有一个 jQuery 方法?

采纳答案by gustavohenke

Answer "translated" from here: Which HTML elements can receive focus?

从这里回答“翻译”:哪些 HTML 元素可以接收焦点?

  • <a>or <area>with href
  • Any form elements which aren't disabled
  • iframes
  • Any element with tabindex
  • <a><area>href
  • 任何未禁用的表单元素
  • 内嵌框架
  • 任何元素 tabindex

Additionaly, I believe that hidden elements can't get focus also.

另外,我相信隐藏元素也无法获得焦点。

Assuming that conditions, the following function may help you (assuming it'll always receive an jQuery element):

假设条件,以下函数可能会帮助你(假设它总是会收到一个 jQuery 元素):

function canFocus( $el ) {
    if ( $el.is( ":hidden" ) || $el.is( ":disabled" ) ) {
        return false;
    }

    var tabIndex = +$el.attr( "tabindex" );
    tabIndex = isNaN( tabIndex ) ? -1 : tabIndex;
    return $el.is( ":input, a[href], area[href], iframe" ) || tabIndex > -1;
}