Document.hasFocus() - Web APIs 编辑

The hasFocus() method of the Document interface returns a Boolean value indicating whether the document or any element inside the document has focus. This method can be used to determine whether the active element in a document has focus.

When viewing a document, an element with focus is always the active element in the document, but an active element does not necessarily have focus. For example, an active element within a popup window that is not the foreground doesn't have focus.

Syntax

var focused = document.hasFocus();

Return value

false if the active element in the document has no focus; true if the active element in the document has focus.

Example

This example checks whether the document has focus every 300 milliseconds. To test the functionality of hasFocus(), click on the button to open a new window, and try switching between the two pages.

HTML

<p id="log">Awaiting focus check.</p>
<button onclick="openWindow()">Open a new window</button>

JavaScript

function checkPageFocus() {
  let body = document.querySelector('body');
  let log = document.getElementById('log');

  if (document.hasFocus()) {
    log.textContent = 'This document has the focus.';
    body.style.background = '#fff';
  }
  else {
    log.textContent = 'This document does not have the focus.';
    body.style.background = '#ccc';
  }
}

function openWindow() {
  window.open('/wiki/', 'MDN', 'width=640,height=320,left=150,top=150');
}

// Check page focus every 300 milliseconds
setInterval(checkPageFocus, 300);

Result

Specifications

SpecificationStatusComment
HTML Living Standard
The definition of 'Document.hasFocus()' in that specification.
Living StandardInitial definition

Browser compatibility

BCD tables only load in the browser

See also

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:142 次

字数:3843

最后编辑:6 年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文