問題描述

我正在尋找一個允許重點關注的 HTML 元素的確定列表,即當 focus()被調用時哪些元素將被放在焦點?

最佳解決方案

沒有一個明確的列表,它取決於瀏覽器。我們唯一的標準是 DOM Level 2 HTML,根據該標準,唯一具有 focus()方法的元素是 HTMLInputElement,HTMLSelectElement,HTMLTextAreaElement 和 HTMLAnchorElement 。這顯然省略了 HTMLButtonElement 和 HTMLAreaElement 。

今天的瀏覽器在 HTMLElement 上定義了 focus(),但是一個元素實際上不會專注,除非它是以下之一:

  • 帶有 href 的 HTMLAnchorElement /HTMLAreaElement

  • HTMLInputElement /HTMLSelectElement /HTMLTextAreaElement /HTMLButtonElement 但不是與 disabled(IE 實際上給你一個錯誤,如果你嘗試),並且文件上傳有不尋常的行為,出於安全原因

  • HTMLIFrameElement(雖然重點沒有做任何有用的事情) 。其他嵌入元素也可能,我還沒有測試它們。

  • 任何具有 tabindex 的元素

… 除非 tabindex-1,這使焦點不可能。

根據瀏覽器,這種行為可能會有其他微妙的例外和補充。

次佳解決方案

在這裏,我有一個基於 bobinceanswer 的 CSS-selector 來選擇任何可重點的 HTML 元素:

  a[href]:not([tabindex='-1']),
  area[href]:not([tabindex='-1']),
  input:not([disabled]):not([tabindex='-1']),
  select:not([disabled]):not([tabindex='-1']),
  textarea:not([disabled]):not([tabindex='-1']),
  button:not([disabled]):not([tabindex='-1']),
  iframe:not([tabindex='-1']),
  [tabindex]:not([tabindex='-1']),
  [contentEditable=true]:not([tabindex='-1'])
  {
      /* your CSS for focusable elements goes here */
  }

或者在 SASS 中更漂亮一點

a[href],
area[href],
input:not([disabled]),
select:not([disabled]),
textarea:not([disabled]),
button:not([disabled]),
iframe,
[tabindex],
[contentEditable=true]
{
    &:not([tabindex='-1'])
    {
        /* your SCSS for focusable elements goes here */
    }
}

我把它添加為一個答案,因為那是我正在尋找的,當 Google 將我重定向到這個 Stackoverflow 問題。

編輯:還有一個選擇器,它是可重點的:

[contentEditable=true]

但是,這很少使用。

參考文獻

注:本文內容整合自 Google/Baidu/Bing 輔助翻譯的英文資料結果。如果您對結果不滿意,可以加入我們改善翻譯效果:薇曉朵技術論壇