简体   繁体   English

Javascript-在写下文本区域之前更改输入字母

[英]Javascript - Change input letter before written down textarea

I'm trying to make a virtual keyboard with jQuery. 我正在尝试使用jQuery创建虚拟键盘。

When I press 'a' in the given textarea, suppose that 'z' should be written instead. 当我在给定的文本区域中按'a'时,假设应该改写'z'

In textarea, I found the whole steps of typing a letter is given by 在textarea中,我发现输入字母的整个步骤由

keyDown event → keyPress event → letter typed in textarea → keyUp event

In my code, I detected the letter in keyPress event and in that event, if the letter was 'a' , I added 'z' in textarea using .val() method. 在我的代码中,我在keyPress event检测到字母,并且在该事件中,如果字母为'a' ,则使用.val()方法在textarea中添加了'z'

If we have the initial string hello in textarea, after keyPress event , we have helloz . 如果我们在textarea中有初始字符串hello ,则在keyPress event ,我们会有helloz Then, before keyUp event occurs, textarea became helloza . 然后,在keyUp event发生之前,textarea成为helloza So I deleted the last letter, 'a' in keyUp event . 所以我删除了keyUp event的最后一个字母'a'

This looks great, and also works well. 这看起来不错,而且效果很好。 But, the problem is TIME DELAY. 但是,问题是时间延迟。

Since steps I wrote above takes a second, 'a' appears quite a while in the textarea. 由于我上面写的步骤需要一秒钟,因此'a'在文本区域中出现的时间相当长。

But the virtual keyboard in Google Translator does not show the original letter. 但是Google翻译器中的虚拟键盘不会显示原始字母。

How can I do this? 我怎样才能做到这一点?

尝试在keyPress事件处理程序中调用event.preventDefault()。

As mentioned, you can use preventDefault() to prevent it from being displayed in your text box, then if you are looking for practical way to get the pressed key's character (instead of the char code), you can do : 如前所述,您可以使用preventDefault()阻止它显示在文本框中,然后,如果您正在寻找获取按键的字符(而不是char代码)的实用方法,则可以执行以下操作:

$('#txt').on('keypress', function (e) {
    var pressedKey = String.fromCharCode(e.keyCode);
    var $txt = $('#txt');
    e.preventDefault();
    if (pressedKey == 'a') {
        $txt.val($txt.val() + 'z');
     }
});

Here is demo: http://jsfiddle.net/82meao9v/1/ 这是演示: http : //jsfiddle.net/82meao9v/1/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM