[英]focus function working in console but in through the code
我正在尝试创建一个允许您输入 IP 地址 (IPv4) 的网页。 我希望每当用户在文本框中添加 3 个数字时,焦点应自动转移到下一个文本框。 为此,我已向文本框提供 onkeypress 事件并调用了一个 JS 函数并向其发送了一个参数。 看看我的代码。
<input onkeypress="check(this)" type="text"
id="<?php if($i==1){echo "5";} else {echo "1";} ?>"
class="form-control" placeholder="First Octate"/>
这是检查功能
function check(element){
if(element.value.length==2){
newId= parseInt(element.id) + 1
document.getElementById(newId.toString()).focus()
}
}
现在,如果我将document.getElementById(newId.toString())
到控制台,它会给我一个有效的元素,如果我对记录的元素使用 focus 方法,我实际上能够改变焦点。 我无法理解的是,如果使用此功能完成,它不会做同样的事情。 我无法根据情况改变焦点
你的代码的问题是焦点没有移动,因为它采取了行动。 您需要添加一个轻微的延迟
function check(element) { if (element.value.length == 2) { var newId = parseInt(element.id) + 1 setTimeout(()=>document.getElementById(newId.toString()).focus(),1); } }
<input onkeypress="check(this)" type="text" id="1" /> <input onkeypress="check(this)" type="text" id="2" /> <input type="text" id="3" />
使用 keyup 事件会更好
function check(element) { if (element.value.length == 3) { var newId = parseInt(element.id) + 1 document.getElementById(newId.toString()).focus(); } }
<input onkeyup="check(this)" type="text" id="1" /> <input onkeyup="check(this)" type="text" id="2" /> <input type="text" id="3" />
现在,如果他们正在打字,这段代码就可以了,如果他们粘贴了一个值,你就有了一个全新的问题需要解决。
尝试将setTimeout
命令添加到您的代码中:
function check(element){ if(element.value.length==2){ newId= parseInt(element.id) + 1 setTimeout(function() { document.getElementById(newId.toString()).focus() }); } }
<input onkeydown="check(this)" type="text" id="1" class="form-control" placeholder="First octet"/> <input onkeydown="check(this)" type="text" id="2" class="form-control" placeholder="Second octet"/> <input onkeydown="check(this)" type="text" id="3" class="form-control" placeholder="Third octet"/> <input onkeydown="check(this)" type="text" id="4" class="form-control" placeholder="Fourth octet"/>
关键事件似乎在发射后重新聚焦目标的输入。 这试图通过等待事件完成触发来解决这个问题,然后它将聚焦下一个输入。
另外,我建议您使用keydown
而不是keypress
- 后者已弃用。
您可以在 window.load 脚本中设置您的事件,并使用 data-attributes 通知您的输入侦听器要侦听的数字数量。 另外,如果你使用 type='number' 你可以确保你会得到数字
window.addEventListener('DOMContentLoaded', () => { let q = document.querySelectorAll('.autofoc'); q.forEach(el => { el.addEventListener('input', e => { let l = +e.target.dataset.len if (e.target.value.length >= l) { e.target.value = e.target.value.slice(0, l) e.target.nextElementSibling.focus() } }) }) })
<input type="number" data-len='3' class="form-control autofoc" placeholder="Area code" /> <input type="number" data-len='3' class="form-control autofoc" placeholder="First 3" /> <input type="number" data-len='4' class="form-control autofoc" placeholder="Last 4" />
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.