JavaScript focus() 方法
最后修改于 2025 年 4 月 2 日
在本文中,我们将探讨 JavaScript 中的 element.focus() 方法。此方法对于表单处理和用户体验至关重要,它允许开发人员以编程方式控制焦点。
基本定义
focus() 方法会在指定元素上设置焦点(如果该元素可以获得焦点)。这通常与 input、select 和 button 等表单元素一起使用。
当一个元素获得焦点时,它就成为页面上的活动元素。这意味着键盘事件默认会定向到该元素。并非所有元素都可以获得焦点 - 只有交互式元素可以。
基本 focus() 示例
此示例演示了如何在页面加载时将焦点设置在输入字段上。
<!DOCTYPE html>
<html>
<head>
<title>Basic focus() Example</title>
</head>
<body>
<input type="text" id="username" placeholder="Enter your name">
<script>
window.onload = function() {
const input = document.getElementById('username');
input.focus();
};
</script>
</body>
</html>
在这个基本示例中,我们有一个文本输入字段。当页面加载时,JavaScript 代码使用 getElementById 来查找输入框并在其上调用 focus()。
这演示了 focus() 的基本用法,通过自动聚焦第一个输入字段来改善用户体验。光标将立即出现在输入字段中。
点击按钮后聚焦
此示例显示了如何在单击按钮后将焦点移到另一个元素。
<!DOCTYPE html>
<html>
<head>
<title>Focus After Click</title>
</head>
<body>
<input type="text" id="firstInput" placeholder="First field">
<button id="myButton">Click to focus next field</button>
<input type="text" id="secondInput" placeholder="Second field">
<script>
const button = document.getElementById('myButton');
const secondInput = document.getElementById('secondInput');
button.addEventListener('click', function() {
secondInput.focus();
});
</script>
</body>
</html>
这里我们有两个输入字段和一个按钮。当按钮被点击时,事件监听器使用 focus() 将焦点移到第二个输入字段。
这演示了如何使用 focus() 以特定顺序引导用户填写表单字段。这对于多步表单尤其有用。
带验证的焦点
此示例演示了如何使用 focus() 来高亮显示无效的表单输入。
<!DOCTYPE html>
<html>
<head>
<title>Focus With Validation</title>
<style>
.invalid { border: 2px solid red; }
</style>
</head>
<body>
<input type="email" id="email" placeholder="Enter your email">
<button id="submitBtn">Submit</button>
<script>
const emailInput = document.getElementById('email');
const submitBtn = document.getElementById('submitBtn');
submitBtn.addEventListener('click', function() {
if (!emailInput.value.includes('@')) {
emailInput.classList.add('invalid');
emailInput.focus();
alert('Please enter a valid email address');
} else {
alert('Form submitted successfully!');
}
});
</script>
</body>
</html>
在此示例中,我们在点击提交按钮时验证电子邮件输入。如果验证失败,我们会添加一个 'invalid' 类并聚焦输入字段。
这表明 focus() 可以通过将用户引导至需要更正的字段来提高表单可用性。视觉反馈有助于用户快速识别和修复错误。
模态对话框中的焦点
此示例显示了如何在打开模态对话框时管理焦点。
<!DOCTYPE html>
<html>
<head>
<title>Modal Focus</title>
<style>
.modal {
display: none;
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
padding: 20px;
background: white;
border: 1px solid #ccc;
z-index: 100;
}
.overlay {
display: none;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0,0,0,0.5);
}
</style>
</head>
<body>
<button id="openModal">Open Modal</button>
<div class="overlay" id="overlay"></div>
<div class="modal" id="modal">
<h2>Modal Dialog</h2>
<input type="text" id="modalInput">
<button id="closeModal">Close</button>
</div>
<script>
const openBtn = document.getElementById('openModal');
const overlay = document.getElementById('overlay');
const modal = document.getElementById('modal');
const closeBtn = document.getElementById('closeModal');
const modalInput = document.getElementById('modalInput');
openBtn.addEventListener('click', function() {
overlay.style.display = 'block';
modal.style.display = 'block';
modalInput.focus();
});
closeBtn.addEventListener('click', function() {
overlay.style.display = 'none';
modal.style.display = 'none';
openBtn.focus();
});
</script>
</body>
</html>
此示例创建了一个模态对话框,当点击一个按钮时出现。当模态框打开时,焦点会自动移到模态框内的输入字段。
当模态框关闭时,焦点会返回到原始按钮。这演示了模态对话框中无障碍和键盘导航的正确焦点管理。
焦点陷阱以提高可访问性
此示例显示了如何创建焦点陷阱以提高可访问性。
<!DOCTYPE html>
<html>
<head>
<title>Focus Trap</title>
<style>
.modal {
display: none;
position: fixed;
top: 50%;
left: 50%;
transform: translate(-50%, -50%);
padding: 20px;
background: white;
border: 1px solid #ccc;
z-index: 100;
}
.overlay {
display: none;
position: fixed;
top: 0;
left: 0;
width: 100%;
height: 100%;
background: rgba(0,0,0,0.5);
}
</style>
</head>
<body>
<button id="openModal">Open Modal</button>
<div class="overlay" id="overlay"></div>
<div class="modal" id="modal">
<h2>Accessible Modal</h2>
<input type="text" id="firstField" placeholder="First field">
<input type="text" id="secondField" placeholder="Second field">
<button id="modalClose">Close</button>
</div>
<script>
const openBtn = document.getElementById('openModal');
const overlay = document.getElementById('overlay');
const modal = document.getElementById('modal');
const closeBtn = document.getElementById('modalClose');
const firstField = document.getElementById('firstField');
const secondField = document.getElementById('secondField');
let focusableElements;
let firstFocusable;
let lastFocusable;
openBtn.addEventListener('click', function() {
overlay.style.display = 'block';
modal.style.display = 'block';
firstField.focus();
// Get all focusable elements
focusableElements = modal.querySelectorAll(
'button, [href], input, select, textarea, [tabindex]:not([tabindex="-1"])'
);
firstFocusable = focusableElements[0];
lastFocusable = focusableElements[focusableElements.length - 1];
});
modal.addEventListener('keydown', function(e) {
if (e.key === 'Tab') {
if (e.shiftKey) {
if (document.activeElement === firstFocusable) {
e.preventDefault();
lastFocusable.focus();
}
} else {
if (document.activeElement === lastFocusable) {
e.preventDefault();
firstFocusable.focus();
}
}
}
});
closeBtn.addEventListener('click', function() {
overlay.style.display = 'none';
modal.style.display = 'none';
openBtn.focus();
});
</script>
</body>
</html>
这个高级示例为模态对话框创建了一个正确的焦点陷阱。当模态框打开时,Tab 键仅在模态框的可聚焦元素之间循环。
此实现对于可访问性很重要,可确保键盘用户不会意外地从模态框中制表。焦点会被捕获,直到模态框被明确关闭。
来源
在本文中,我们展示了如何在 JavaScript 中使用 focus() 方法。此方法对于表单处理和创建可访问的 Web 界面至关重要。
作者
列出 所有 JS DOM 教程。