[英]How do I know, via key event code, if the character just entered in a <textarea> is lower or upper case?
I'm trying to capture the character just entered into a . 我正在尝试捕获刚刚输入到中的字符。 But I can only get which key is pressed via key event like keydown or keyup, not knowing if it's lower case or upper case.
但是我只能通过按键事件(例如keydown或keyup)来获得按下哪个键的信息,而不知道它是小写还是大写。
For example, when I input A or a, the event key codes for keydown are all 65. I thought of using val() to get the string in the and get the last character of it. 例如,当我输入A或a时,keydown的事件键代码全部为65。我想到了使用val()来获取中的字符串并获取其最后一个字符。 But that is too slow and memory consuming, since I want to record every keyboard event while the user is typing.
但这太慢且占用内存,因为我想在用户键入时记录每个键盘事件。
So is there a way I can simply get the last entered character? 那么有什么办法可以让我简单地获取最后输入的字符? Thanks in advance!
提前致谢!
Try this: 尝试这个:
var p = $('#log')[0]; $("#textarea").on("keypress", function(e) { p.textContent = ''; var k = e.keyCode || e.which; var character = String.fromCharCode(k); if (!isNaN(character * 1)) { p.textContent += 'character is numeric'; } else { if (character == character.toUpperCase()) { p.textContent += 'UPPER case true'; } if (character == character.toLowerCase()) { p.textContent += 'lower case true'; } } });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <textarea id="textarea"></textarea> <p id="log"></p>
I see what you mean about the shiftKey 我明白你对shiftKey的意思
var myObj = $('#myTextarea');
function isLetter(char){
if ((char.toLowerCase() !== char) || (char.toUpperCase() !== char)) {
return true;
}
return;
}
myObj.keypress(function( event ){
var text = myObj.val();
var char = text.charAt(text.length-1);
if (!event.shiftKey && isLetter(char)) {
if (char == char.toUpperCase()) {
console.log('Upper');
}
if (char == char.toLowerCase()) {
console.log('Lower');
}
}
});
try: 尝试:
<textarea id="area1"></textarea>
window.onload = function () {
document.getElementById("area1").onkeypress = function(event){
var code = event.which;
if ((code >= 65) && (code <= 90)) {
alert('Upper');
}
else if ((code >= 97) && (code <= 122)) {
alert('Lower');
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.