按下按键或按字符时,如何检测所插入字符的位置?

4

我不确定这是否可行(看起来好像不行),但我正在尝试找到一种方法,在HTML输入标签的onKeyDown或onKeyPress事件中检测即将产生的值。

使用这些事件对我很重要。我不能只使用onKeyUp,因为那时输入框已经发生了变化。我想防止它在第一时间发生。我也尝试将按下的键字符添加到字符串末尾,但那并不能解决你在输入字段开头输入字符的情况。

有什么想法吗?我已经寻找了一段时间,似乎不可能,但我想问问。

2个回答

8

我这里有两个版本,一个是用jQuery实现的,另一个只使用JavaScript。

$("#inputJQuery").on("keydown", function(ev){
 console.log("jQuery value:", $(this).val()); // this is the value before the key is added
 console.log("jQuery selectionStart:", this.selectionStart); // the position where the character will be inserted
 console.log("jQuery selectionEnd:", this.selectionEnd); // if has a selection this value will be different than the previous
})

document.querySelector("#inputVanilla").onkeydown = function(ev){
 console.log("VANILLA value:", this.value); // this is the value before the key is added
 console.log("VANILLA selectionStart:", this.selectionStart); // the position where the character will be inserted
 console.log("VANILLA selectionEnd:", this.selectionEnd); // if has a selection this value will be different than the previous
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<input id="inputJQuery" type="text"/>
<input id="inputVanilla" type="text"/>


我之前没有提到这个,因为我没有意识到这很重要,但我的输入类型是“数字”。看起来这只适用于文本输入。你知道有什么解决方法吗?如果没有,我就只能切换到文本类型了。 - Carlos Rodriguez
不可能针对数字类型的输入。https://dev59.com/mGEi5IYBdhLWcg3wjczE#21959157 - Manuel Sánchez

2

只需在按键事件中检查valuelength即可。这也适用于删除字符。

您还可以通过条件语句来检查此项,如果超过一定数量的字符,则返回false以防止用户输入。请注意,您可能需要检查backspacedelete键(分别是keyCodes 846),以便在达到最大长度后能够删除键。

var input = document.getElementById('input');
input.onkeydown = function(e) {
  console.log(input.value.length);
  if (input.value.length == 10) {
    if (e.keyCode === 8 || e.keyCode === 46) {
      return true;
    } else {
      return false;
    }
  }
}
<input id="input">

希望这有所帮助! :)

谢谢回复,但似乎检查value.length只返回应用新字符之前输入的长度。这并不能帮助我确定键添加到字符串的哪个位置。例如,假设有人键入数字100。然后在前面添加1(使文本框变为1100)。我需要知道设置为输入之前的新值,以便我可以防止它。我不确定您的答案如何实现这一点。谢谢。 - Carlos Rodriguez
1
哦,我明白了 - 我的错。你可以始终检查 input.value 本身,比如 if (input.value == 1100) { return false; },不过这只会在他们实际输入后才进行检查。话虽如此,你真的不应该阻止他们输入任何东西,而是在表单提交(或逻辑处理)后验证输入。 - Obsidian Age
我不确定我同意那个观点。如果你将输入类型设置为“数字”,Chrome会完全阻止任何非数字输入。我只是试图在这种思路的基础上进行扩展。例如,只要负数在正确的位置上,就允许其存在。 - Carlos Rodriguez
1
哦,是的,你肯定可以在前端进行验证。虽然防止实际输入相当不寻常,而且我不确定是否真的可以预防输入被提前键入。个人做法是检查 blur() 事件,如果输入无法接受,则添加内联错误消息。然后用户就知道他们需要更改它。不过,仅进行前端验证是绝对不够的,你应该始终在后端进行验证(不要忘记在提交表单后可以操作数据)。 - Obsidian Age
是的,后端是一个REST API,所以我不假设请求甚至来自于这个页面,或者说“一个页面”,哈哈。 - Carlos Rodriguez

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接