我需要在输入文本框之前捕获输入内容并根据需要进行编辑。我用 javascript 和 jQuery 编写。
我有一个文本框,我想检测何时键入“#”字符 - 在将其写入文本框之前 - 然后捕获之后(也在写入之前)的所有键入,直到我得到另一个“#”。
我在网上看过很多关于如何使用“keypress”来检测特定键何时被键入的例子,但我不知道如何在将这两个特殊键之间键入的所有文本写入文本框。
我可以使用关于该主题的任何帮助!
最佳答案
在第一种情况下,所有字符的输入都被阻止,然后在您可以编辑的文本变量中,然后为输入字段分配一个值
$('#typehere').on("keypress",function(e){
e.preventDefault();
if(e.which == "#".charCodeAt(0)){
if(listening){
listening= false;
//do what you want with the text
alert("no more listening: "+text);
}else{
listening = true;
alert("listening");
}
return true;
}
if(listening)
text+= String.fromCharCode(e.which);
});
试试 fiddle https://jsfiddle.net/42fns28a/
在第二种情况下,您可以在输入字段中键入直到您的特殊字符被按下,您可以键入并编辑您想要的内容,直到第二次按下特殊字符
$('#typehere').on("keypress",function(e){
if(e.which == "#".charCodeAt(0)){
e.preventDefault();
if(listening){
listening= false;
//do what you want with the text
$(this).val($(this).val()+text);
alert("no more listening: "+text);
}else{
listening = true;
alert("listening");
}
return true;
}
if(listening){
e.preventDefault();
text+= String.fromCharCode(e.which);
}
});
第二 fiddle https://jsfiddle.net/2cdjoq6u/
关于javascript - 按下特定键后如何捕获打字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31582320/