JavaScript 聚焦事件

摘要:在本教程中,您将学习关于 JavaScript 聚焦事件的知识,这些事件会跟踪用户所关注的元素。

JavaScript 聚焦事件介绍

当元素获得或失去焦点时,focus 事件就会触发。以下这两个是主要的焦点事件

  • focus 当元素获得焦点时触发。
  • blur 当元素失去焦点时触发。

focusinfocusoutfocusblur 同时触发,但是,它们会冒泡,而 focusblur 不会。

以下元素是可聚焦的

  • 窗口 当您使用 Alt+Tab 或单击窗口将其置于最前面时,它会获得焦点,当您将其发送回后,它会失去焦点。
  • 链接 当您使用鼠标或键盘时。
  • 表单字段 例如,当您使用键盘或鼠标时,输入文本。
  • 具有tabindex 的元素,同样在您使用键盘或鼠标时。

JavaScript 聚焦事件示例

以下示例演示了如何处理 focusblur 事件。当您将焦点移动到 password 字段时,背景会变为 黄色。如果您将鼠标移动到 username 字段,背景会变为 白色

<!DOCTYPE html>
<html>
<head>
    <title>JavaScript Focus Events</title>
</head>
<body>
    <p>Move focus to the password field to see the effect:</p>

    <form id="form">
        <input type="text" placeholder="username">
        <input type="password" placeholder="password">
    </form>

    <script>
        const pwd = document.querySelector('input[type="password"]');

        pwd.addEventListener('focus', (e) => {
            e.target.style.backgroundColor = 'yellow';
        });

        pwd.addEventListener('blur', (e) => {
            e.target.style.backgroundColor = '';
        });
    </script>
</body>
</html>Code language: HTML, XML (xml)

总结

  • 使用 focus 事件来处理元素在获得或失去焦点时的状态。
本教程对您有帮助吗?