在JavaScript中,使文本框(<input type="text">
或 <textarea>
)获得焦点可以通过调用其 focus()
方法来实现。以下是相关的基础概念、优势、应用场景以及示例代码:
焦点(Focus):在Web页面中,焦点是指用户当前正在与之交互的元素。获得焦点的元素会响应键盘事件。
focus() 方法:这是HTMLInputElement和HTMLTextAreaElement接口的一个方法,用于将焦点设置到指定的元素上。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Focus Example</title>
</head>
<body>
<form>
<label for="username">Username:</label>
<input type="text" id="username" name="username">
<br><br>
<label for="password">Password:</label>
<input type="password" id="password" name="password">
<br><br>
<button type="submit">Submit</button>
</form>
<script>
// 页面加载完成后,自动聚焦到用户名输入框
window.onload = function() {
document.getElementById('username').focus();
};
// 表单提交时,如果用户名为空,聚焦到用户名输入框并显示错误信息
document.querySelector('form').addEventListener('submit', function(event) {
var username = document.getElementById('username').value;
if (username === '') {
event.preventDefault(); // 阻止表单提交
document.getElementById('username').focus();
alert('Username cannot be empty!');
}
});
</script>
</body>
</html>
问题:为什么页面加载后文本框没有自动获得焦点?
原因:
focus()
方法调用时机不对,可能在DOM元素还未加载完成时调用。focus()
方法未执行。解决方法:
focus()
方法,可以使用 window.onload
事件或 DOMContentLoaded
事件。示例:
document.addEventListener('DOMContentLoaded', function() {
document.getElementById('username').focus();
});
通过以上方法,可以确保文本框在页面加载后自动获得焦点,并且在表单验证失败时也能正确聚焦到错误输入框。
领取专属 10元无门槛券
手把手带您无忧上云