如何防止“后口音"在输入文字中 [英] how to prevent "post accent" in input text

查看:132
本文介绍了如何防止“后口音"在输入文字中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我相信这是一个简单的方法,但是在Google搜索几个小时后我找不到任何答案(也许我无法在搜索中使用正确的词:-P)

I believe this is an easy one, but I couldn't find any answer after a couple of hours searching on google (maybe I wasn't able to use the correct words in the search :-P)

我有一个javascript方法,可以防止用户用数字以外的其他字符填充文本框,如下面的代码所示,它用于KeyDown事件:

I have a javascript method that prevents the user to fill the textbox with other characters than numbers, as it can be seen in the code below, and it's used in KeyDown event:

function checkNumberInput(e) {
  // Allow: backspace, delete, tab, escape, enter and .
  if ($.inArray(e.keyCode, [46, 8, 9, 27, 13, 110]) !== -1 ||
      // Allow: Ctrl+A, Command+A
      (e.keyCode == 65 && (e.ctrlKey === true || e.metaKey === true)) ||
      // Allow: home, end, left, right, down, up
      (e.keyCode >= 35 && e.keyCode <= 40)) {
    // let it happen, don't do anything
    return;
  }
  // Ensure that it is a number and stop the keypress
  if ((e.shiftKey || (e.keyCode < 48 || e.keyCode > 57)) && (e.keyCode < 96 || e.keyCode > 105)) {
    e.preventDefault();
  }
}

问题在于,如果用户键入等待"第二个键的重音字符(例如〜´` ^),则紧随其后键入数字时,它会出现在文本框中.

The problem is that, if the user types accent characters that "waits" a second key (such as ~´`^), it appears in the textbox when a number is typed right after.

例如:

a) types 1 => [1________]
b) types ~ => [1________]
c) types 3 => [1~3______]

如何防止这种情况发生?预先感谢.

How can I prevent this from happening? Thanks in advance.

推荐答案

您是说'a转换为а́吗? 这是系统内置的,不能更改.
您可以做的就是在此之后检查输入.这样,您还可以防止鼠标粘贴:

Do you mean that ' and a are converted to а́? This is built in the system, you cannot change that.
What you can do is check the input after that. This way you'll also prevent paste with mouse:

$('input').on('keydown', checkNumberInput).on('blur focus', function(){
    var val = $('input').val();

    // now remove everything that is not allowed
    val = val.replace(/[^0-9.]+/g, '');

    $('input').val(val);
})

(确切的实现绝对不是完美的,只是为了说明正在发生的事情)

(The exact implementation is deffinitely not perfect, just to illustrate what's going on)

https://jsfiddle.net/5afwdhzx/

关于真正的即时修复-给此闭包起一个名字,并在keyDown函数中稍稍延迟地调用它,例如上面的@haroldo.

About really instant fix - give this closure a name and call it inside the keyDown function with some short delay, like @haroldo said above.

https://jsfiddle.net/5afwdhzx/1/

这篇关于如何防止“后口音"在输入文字中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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