要通过按“Enter”键将焦点设置在下一个“启用”输入框上,可以使用JavaScript来实现这一功能。以下是具体的步骤和示例代码:
<input>
、<textarea>
等。以下是一个简单的示例,展示了如何通过JavaScript监听“Enter”键,并将焦点移动到下一个启用的输入框。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Auto Focus Next Input</title>
<script>
document.addEventListener('DOMContentLoaded', function() {
document.querySelectorAll('input[type="text"]').forEach(function(input) {
input.addEventListener('keydown', function(event) {
if (event.key === 'Enter') {
event.preventDefault(); // 阻止默认行为
var nextInput = this.nextElementSibling;
while (nextInput && !nextInput.matches('input[type="text"]:enabled')) {
nextInput = nextInput.nextElementSibling;
}
if (nextInput) {
nextInput.focus();
}
}
});
});
});
</script>
</head>
<body>
<form>
<input type="text" id="input1" placeholder="Input 1">
<input type="text" id="input2" placeholder="Input 2" disabled>
<input type="text" id="input3" placeholder="Input 3">
<input type="text" id="input4" placeholder="Input 4">
</form>
</body>
</html>
keydown
事件监听器。event.preventDefault()
来阻止表单提交或其他默认行为。nextElementSibling
属性遍历后续兄弟节点,直到找到一个启用的文本输入框。focus()
方法来设置焦点。这种方法确保了只有启用的输入框会接收焦点,从而提供了一个流畅的用户体验。
领取专属 10元无门槛券
手把手带您无忧上云