文档:hasFocus() 方法

Baseline 已广泛支持

此特性已相当成熟,可在许多设备和浏览器版本上使用。自 ⁨2015 年 7 月⁩以来,各浏览器均已提供此特性。

Document 接口的 hasFocus() 方法返回一个布尔值,指示文档或文档中的任何元素是否具有焦点。此方法可用于确定文档中活动元素是否具有焦点。

注意: 查看文档时,具有焦点的元素始终是文档中的 活动元素,但活动元素不一定具有焦点。例如,在非前景的弹出窗口中的活动元素没有焦点。

语法

js
hasFocus()

参数

无。

返回值

如果文档中的活动元素没有焦点,则为 false;如果文档中的活动元素具有焦点,则为 true

示例

检查文档是否具有焦点

下面的示例检查文档是否具有焦点。一个名为 checkPageFocus() 的函数根据 document.hasFocus() 的结果更新一个段落元素。打开新窗口将导致文档失去焦点,切换回原始窗口将导致文档重新获得焦点。

html
<p id="log">Focus check results are shown here.</p>
<button id="newWindow">Open new window</button>
js
const body = document.querySelector("body");
const log = document.getElementById("log");

function checkDocumentFocus() {
  if (document.hasFocus()) {
    log.textContent = "This document has focus.";
    body.style.background = "white";
  } else {
    log.textContent = "This document does not have focus.";
    body.style.background = "gray";
  }
}

function openWindow() {
  window.open(
    "https://mdn.org.cn/",
    "MDN",
    "width=640,height=320,left=150,top=150",
  );
}

document.getElementById("newWindow").addEventListener("click", openWindow);
setInterval(checkDocumentFocus, 300);

规范

规范
HTML
# dom-document-hasfocus-dev

浏览器兼容性

另见