ZetCode

JavaScript document.hasFocus

最后修改于 2025 年 4 月 2 日

在本文中,我们将探讨 JavaScript 中的 document.hasFocus() 方法。此方法检查文档或其中的任何元素是否具有焦点,这对于改善用户体验和可访问性非常有用。

基本定义

document.hasFocus() 方法返回一个布尔值,指示文档或其中的任何元素当前是否具有焦点。这有助于确定用户是否正在积极与页面交互。

当文档具有焦点时,这意味着用户的注意力集中在页面上。这对于需要在用户切换到另一个标签页或窗口时暂停动画或通知的应用程序特别有用。

基本 hasFocus 检查

本示例演示了如何对文档执行基本的焦点检查。

index.html
<!DOCTYPE html>
<html>
<head>
    <title>Basic hasFocus Check</title>
</head>
<body>

<button onclick="checkFocus()">Check Focus</button>
<p id="result"></p>

<script>
    function checkFocus() {
        const hasFocus = document.hasFocus();
        document.getElementById('result').textContent = 
            `Document has focus: ${hasFocus}`;
    }
</script>

</body>
</html>

在此基本示例中,单击按钮会调用 checkFocus(),该函数使用 document.hasFocus() 来检查文档是否具有焦点。结果显示在段落元素中。

这演示了使用 hasFocus() 的最简单方法。如果文档具有焦点,则该方法返回 true,否则返回 false

窗口焦点事件

本示例显示了如何检测窗口何时获得或失去焦点。

index.html
<!DOCTYPE html>
<html>
<head>
    <title>Window Focus Event</title>
</head>
<body>

<p id="status">Window is focused</p>

<script>
    window.addEventListener('focus', function() {
        document.getElementById('status').textContent = 
            'Window is focused';
    });

    window.addEventListener('blur', function() {
        document.getElementById('status').textContent = 
            'Window lost focus';
    });
</script>

</body>
</html>

在这里,我们使用窗口对象的 focusblur 事件来跟踪窗口何时获得或失去焦点。状态显示在段落元素中。

虽然没有直接使用 hasFocus(),但这展示了相关的焦点管理。这些事件可以与 hasFocus() 结合使用以进行更复杂的焦点跟踪。

在 blur 时暂停动画

本示例演示了如何在窗口失去焦点时暂停动画。

index.html
<!DOCTYPE html>
<html>
<head>
    <title>Pause Animation on Blur</title>
    <style>
        #box {
            width: 100px;
            height: 100px;
            background-color: red;
            position: relative;
            animation: move 2s infinite alternate;
        }
        @keyframes move {
            from { left: 0; }
            to { left: 200px; }
        }
    </style>
</head>
<body>

<div id="box"></div>

<script>
    const box = document.getElementById('box');
    let animationPaused = false;

    window.addEventListener('blur', function() {
        box.style.animationPlayState = 'paused';
        animationPaused = true;
    });

    window.addEventListener('focus', function() {
        if (animationPaused) {
            box.style.animationPlayState = 'running';
            animationPaused = false;
        }
    });
</script>

</body>
</html>

在此示例中,一个红色的方框来回动画。当窗口失去焦点时,动画会暂停。当窗口重新获得焦点时,动画会恢复。

这演示了焦点检测的一个实际用例。当用户不关注页面时暂停动画可以提高性能和用户体验。

基于焦点的通知

本示例显示了窗口重新获得焦点时如何显示通知。

index.html
<!DOCTYPE html>
<html>
<head>
    <title>Focus Notification</title>
</head>
<body>

<div id="notification" style="display: none;">
    Welcome back!
</div>

<script>
    let lastBlurTime = null;

    window.addEventListener('blur', function() {
        lastBlurTime = new Date();
    });

    window.addEventListener('focus', function() {
        if (lastBlurTime) {
            const timeAway = Math.floor(
                (new Date() - lastBlurTime) / 1000
            );
            const notification = document.getElementById('notification');
            notification.textContent = `Welcome back! You were away for ${timeAway} seconds.`;
            notification.style.display = 'block';
            setTimeout(() => {
                notification.style.display = 'none';
            }, 3000);
        }
    });
</script>

</body>
</html>

在这里,我们跟踪窗口何时失去焦点,并在它重新获得焦点时显示欢迎消息以及离开的持续时间。通知会在 3 秒后消失。

这表明焦点检测可用于创建用户友好的功能。该示例结合了 blurfocus 事件以及计时计算。

实时焦点监控

本示例演示了使用 hasFocus() 进行连续焦点监控。

index.html
<!DOCTYPE html>
<html>
<head>
    <title>Real-Time Focus Monitor</title>
</head>
<body>

<p id="status">Checking focus...</p>

<script>
    function updateFocusStatus() {
        const hasFocus = document.hasFocus();
        document.getElementById('status').textContent = 
            `Document ${hasFocus ? 'has' : 'does not have'} focus`;
    }

    // Check focus initially
    updateFocusStatus();

    // Set up periodic checking
    setInterval(updateFocusStatus, 1000);

    // Also update on focus/blur events
    window.addEventListener('focus', updateFocusStatus);
    window.addEventListener('blur', updateFocusStatus);
</script>

</body>
</html>

本示例连续监控文档焦点状态。它每秒检查一次焦点,并通过事件监听器立即更新焦点变化。

这演示了一种全面的焦点监控方法。定期检查和事件监听器的组合可确保准确且响应迅速的焦点跟踪。

来源

MDN hasFocus 文档

在本文中,我们展示了如何在 JavaScript 中使用 document.hasFocus()。此方法对于创建能够适应用户注意力的响应式 Web 应用程序非常有用。

作者

我叫 Jan Bodnar,是一名热情的程序员,拥有丰富的编程经验。我自 2007 年以来一直撰写编程文章。至今,我已撰写了 1,400 多篇文章和 8 本电子书。我在教授编程方面拥有十多年的经验。

列出 所有 JS DOM 教程