OnKeyDown或KeyPress,检测插入字符的位置 [英] OnKeyDown or KeyPress, detect the location of the inserted character

查看:47
本文介绍了OnKeyDown或KeyPress,检测插入字符的位置的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I don't know if this is possible (it looks like it's not), but I'm trying to find a way to detect, inside the onKeyDown or onKeyPress event of an HTML input tag, what the resulting value will be.

使用这些事件很重要.我不能只使用onKeyUp,因为到那时输入将已经更改.我想从一开始就防止它发生.我还尝试将按下的键字符附加到字符串的末尾,但这不能解决您在输入字段的字符串开头键入字符的情况.

It's important that I use these events. I can't just use onKeyUp, because by then the input will have already changed. I want to prevent it from happening in the first place. I've also tried appending the pressed key character to the end of the string, but that doesn't account for cases where you typed a character in the beginning of the string in the input field.

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

Any ideas? I've looked for a while and it doesn't seem possible but I figured I'd ask.

推荐答案

在这里,我有2个版本,一个使用jQuery,另一个使用JavaScript.

Here I have 2 versions, one with jQuery and other with JavaScript alone.

$("#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"/>

这篇关于OnKeyDown或KeyPress,检测插入字符的位置的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆