document.hasFocus
Baseline Widely available
This feature is well established and works across many devices and browser versions. It’s been available across browsers since July 2015.
Document.hasFocus()
方法返回一个 Boolean
,表明当前文档或者当前文档内的节点是否获得了焦点。该方法可以用来判断当前文档中的活动元素是否获得了焦点。
备注: 当查看一个文档时,当前文档中获得焦点的元素一定是当前文档的活动元素,但一个文档中的活动元素不一定获得了焦点.。例如,一个在后台的窗口中的活动元素一定没有获得焦点。
语法
js
hasFocus()
返回值
如果当前文档的活动元素获得了焦点,返回 true
,否则返回 false。
示例
html
<!doctype html>
<html>
<head>
<style type="text/css">
#message {
font-weight: bold;
}
</style>
<script type="text/javascript">
setInterval("CheckPageFocus()", 200);
function CheckPageFocus() {
var info = document.getElementById("message");
if (document.hasFocus()) {
info.innerHTML = "该页面获得了焦点。";
} else {
info.innerHTML = "该页面没有获得焦点。";
}
}
function OpenWindow() {
window.open(
"http://developer.mozilla.org/",
"mozdev",
"width=640, height=300, left=150, top=260",
);
}
</script>
</head>
<body>
document.hasFocus 演示<br /><br />
<div id="message">等待用户操作</div>
<br />
<button onclick="OpenWindow()">打开一个新窗口</button>
</body>
</html>
浏览器兼容性
Report problems with this compatibility data on GitHubdesktop | mobile | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|
hasFocus |
Legend
Tip: you can click/tap on a cell for more information.
- Full support
- Full support
- Partial support
- Partial support
- Has more compatibility info.
The compatibility table on this page is generated from structured data. If you'd like to contribute to the data, please check out https://github.com/mdn/browser-compat-data and send us a pull request.