OnKeyDown 或 KeyPress,检测插入字符的位置

Car*_*uez 3 html javascript

我不知道这是否可能(看起来不可能),但我试图找到一种方法来检测 HTML 输入标签的 onKeyDown 或 onKeyPress 事件中的结果值是什么。

我使用这些事件很重要。我不能只使用 onKeyUp,因为到那时输入已经改变了。我想首先防止它发生。我还尝试将按下的键字符附加到字符串的末尾,但这并没有考虑您在输入字段的字符串开头键入字符的情况。

有任何想法吗?我已经找了一段时间,似乎不可能,但我想我会问。

小智 7

这里我有 2 个版本,一个使用 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
}
Run Code Online (Sandbox Code Playgroud)
<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"/>
Run Code Online (Sandbox Code Playgroud)