ZetCode

JavaScript blur() 方法

最后修改于 2025 年 4 月 2 日

在本文中,我们将探讨 JavaScript 中的 blur() 方法。此方法可从当前元素移除键盘焦点,这对于创建直观的用户界面和表单处理至关重要。

基本定义

blur() 方法可从当前元素移除键盘焦点。它通常与输入框、按钮和链接等表单元素一起使用,以编程方式控制焦点行为。

当元素失去焦点时,会触发 blur 事件。此方法相当于用户在页面其他位置单击的操作。

基本 blur() 示例

此示例演示了如何使用 blur() 从输入字段中移除焦点。

index.html
<!DOCTYPE html>
<html>
<head>
    <title>Basic blur() Example</title>
</head>
<body>

<input type="text" id="myInput" placeholder="Click then blur">
<button onclick="removeFocus()">Remove Focus</button>

<script>
    function removeFocus() {
        const input = document.getElementById('myInput');
        input.blur();
    }
</script>

</body>
</html>

在这个基本示例中,我们有一个输入字段和一个按钮。当单击按钮时,将调用 removeFocus 函数,该函数使用 blur() 从输入字段中移除焦点。

这演示了 blur() 控制焦点行为的基本用法。该方法在当前具有焦点的元素对象上调用。

使用 blur() 进行表单验证

此示例演示了在离开字段时如何使用 blur() 进行表单验证。

index.html
<!DOCTYPE html>
<html>
<head>
    <title>Form Validation</title>
    <style>
        .error { border: 2px solid red; }
    </style>
</head>
<body>

<input type="email" id="email" placeholder="Enter email">
<p id="error" style="color:red"></p>

<script>
    const emailInput = document.getElementById('email');
    const errorMsg = document.getElementById('error');
    
    emailInput.addEventListener('blur', function() {
        if (!this.value.includes('@')) {
            this.classList.add('error');
            errorMsg.textContent = 'Please enter a valid email';
        } else {
            this.classList.remove('error');
            errorMsg.textContent = '';
        }
    });
</script>

</body>
</html>

在此,我们在电子邮件输入框失去焦点时对其进行验证。blur 事件监听器会检查输入内容是否包含“@”符号,如果没有则显示错误。

这演示了 blur 事件如何触发验证。如果需要,实际的 blur() 方法将用于强制进行验证。

防止焦点劫持

此示例演示了如何使用 blur() 来防止弹出窗口劫持焦点。

index.html
<!DOCTYPE html>
<html>
<head>
    <title>Prevent Focus Stealing</title>
    <style>
        #modal { display: none; position: fixed; top: 50%; left: 50%; 
                transform: translate(-50%, -50%); padding: 20px; 
                background: white; border: 1px solid #ccc; }
    </style>
</head>
<body>

<button id="openModal">Open Modal</button>
<div id="modal">
    <h3>Important Message</h3>
    <p>Please read this carefully</p>
    <button id="closeModal">Close</button>
</div>

<script>
    const openBtn = document.getElementById('openModal');
    const modal = document.getElementById('modal');
    const closeBtn = document.getElementById('closeModal');
    
    openBtn.addEventListener('click', function() {
        modal.style.display = 'block';
        openBtn.blur(); // Remove focus from the triggering button
    });
    
    closeBtn.addEventListener('click', function() {
        modal.style.display = 'none';
    });
</script>

</body>
</html>

在此示例中,单击“打开模态框”按钮会显示一个模态对话框,同时使用 blur() 从按钮中移除焦点。这样可以防止按钮在打开模态框后保持焦点。

此技术通过确保焦点不会“卡在”隐藏或非活动元素上,从而提高了可访问性。这是模态框实现中的常见模式。

自定义下拉菜单与 blur()

此示例演示了如何创建在失去焦点时关闭的自定义下拉菜单。

index.html
<!DOCTYPE html>
<html>
<head>
    <title>Custom Dropdown</title>
    <style>
        .dropdown {
            position: relative;
            display: inline-block;
        }
        .dropdown-content {
            display: none;
            position: absolute;
            background: #f9f9f9;
            min-width: 160px;
            box-shadow: 0 8px 16px rgba(0,0,0,0.2);
            z-index: 1;
        }
        .dropdown:hover .dropdown-content {
            display: block;
        }
    </style>
</head>
<body>

<div class="dropdown" tabindex="0">
    <button>Select Option</button>
    <div class="dropdown-content">
        <a href="#">Option 1</a>
        <a href="#">Option 2</a>
        <a href="#">Option 3</a>
    </div>
</div>

<script>
    const dropdown = document.querySelector('.dropdown');
    
    dropdown.addEventListener('blur', function() {
        this.querySelector('.dropdown-content').style.display = 'none';
    });
</script>

</body>
</html>

在此,我们创建了一个自定义下拉菜单,当它失去焦点时会关闭。blur 事件监听器会在焦点移出下拉菜单容器时隐藏下拉菜单内容。

这演示了 blur 事件如何帮助管理交互式组件。tabindex 属性使 div 可聚焦。

单页应用中的焦点管理

此示例演示了如何在 SPA 中使用 blur() 来更好地管理焦点。

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

<nav>
    <button id="home">Home</button>
    <button id="about">About</button>
    <button id="contact">Contact</button>
</nav>
<div id="content">Home Content</div>

<script>
    const navButtons = document.querySelectorAll('nav button');
    const contentDiv = document.getElementById('content');
    
    navButtons.forEach(button => {
        button.addEventListener('click', function() {
            // Remove focus from all nav buttons
            navButtons.forEach(btn => btn.blur());
            
            // Update content based on clicked button
            contentDiv.textContent = `${this.textContent} Content`;
        });
    });
</script>

</body>
</html>

在这个类似 SPA 的示例中,单击导航按钮会更新内容,同时移除所有按钮的焦点。这可以防止焦点指示器保留在非活动导航项上。

此技术通过在导航操作后清理焦点状态,从而改善了单页应用程序的用户体验。对于键盘用户来说尤其有用。

来源

MDN blur() 文档

在本文中,我们展示了如何在 JavaScript 中使用 blur() 方法。此方法对于控制焦点行为以及创建可访问、用户友好的界面至关重要。

作者

我的名字是 Jan Bodnar,我是一名充满热情的程序员,拥有丰富的编程经验。我从 2007 年开始撰写编程文章。迄今为止,我已撰写了 1400 多篇文章和 8 本电子书。我在教学编程方面拥有十多年的经验。

列出 所有 JS DOM 教程