HTML - DOM Document 的 hasFocus() 方法



**hasFocus()** 方法用於確定文件或文件內任何元素是否具有焦點。它返回一個布林值,其中 true 表示文件/元素具有焦點,false 表示否則。它表示活動元素是否處於焦點狀態。

語法

document.hasFocus();

引數

此方法不接受任何引數。

返回值

它返回一個布林值,表示元素或文件是否具有焦點。

HTML DOM Document 'hasFocus()' 方法示例

以下示例說明了 hasFocus() 方法。

檢查文件焦點

以下示例顯示 HTML 文件是否具有焦點。

<!DOCTYPE html>
<html lang="en">
<head>
    <title>
        HTML DOM document hasFocus() Method
    </title>
</head>
<body>
    <p>
        Click the button below to check if 
        document is in focus or not.
    </p>
    <button onclick="fun()">
        Click me
    </button>
    <p id="focus"></p>
    <script>
        setInterval("checkFocus()", 1);
        function fun() {
            let x = document.getElementById("focus");
            if (document.hasFocus()) {
                x.innerHTML = "FOCUSED";
            }
            else {
                x.innerHTML = "NOT FOCUSED";
            }
        }
    </script>
</body>
</html>

更改文字顏色

在以下示例中,如果文件具有焦點,則文件的文字顏色會發生變化。

<!DOCTYPE html>
<html lang="en">
<head>
    <title>
        HTML DOM document hasFocus() Method
    </title>
</head>
<body>
    <p>
        Click the button below to check 
        if document is in focus or not.
    </p>
    <button onclick="fun()">
        Click me
    </button>
    <p id="focus">Welcome to Tutorials Point...</p>
    <script>
        setInterval("checkFocus()", 1);
        function fun() {
            let x = document.getElementById("focus");
            if (document.hasFocus()) {
                x.style.color = "#04af2f";
            }
            else {
                x.style.color = "yellow";
            }
        }
    </script>
</body>
</html>

支援的瀏覽器

方法 Chrome Edge Firefox Safari Opera
hasFocus() 是 2 是 12 是 3 是 4 是 15
html_dom_document_reference.htm
廣告