文件:hasFocus() 方法
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.club.tw/",
"MDN",
"width=640,height=320,left=150,top=150",
);
}
document.getElementById("newWindow").addEventListener("click", openWindow);
setInterval(checkDocumentFocus, 300);
規範
| 規範 |
|---|
| HTML # dom-document-hasfocus-dev |
瀏覽器相容性
載入中…