Keydown允许数字,但不能在iPhone上移动符号 [英] Keydown allowing numbers but not shift symbols on iPhone

查看:108
本文介绍了Keydown允许数字,但不能在iPhone上移动符号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个事件绑定到一个只允许数字的输入。简体:

 函数(e){
if(-1 === [48,49,50,51 ,52,53,54,55,56,57] .indexOf(e.keyCode)){
e.preventDefault();






这很好,但如果有人键入 @ $ 等,keyCode仍然是相同的,并且事件默认不被阻止。 / p>

在物理键盘上,我可以通过检查 e.shiftKey 来防止这种情况发生。但是,在iOS 虚拟键盘上,即使对于< input type,也存在一些这些字符(例如 $ ) =数字> ,他们可以直接输入。他们的keyCode是一样的,但它看起来像 e.shiftKey 仍然是错误的。



我可以接受的解决方案:


  • 让虚拟键盘本身不显示这些字符(即仅限于显示数字和句点/小数)

  • 检测一个无效的虚拟键是否被按下并禁止事件行为
  • 确定一个无效字符是添加到输入的值并在这种情况下抑制事件行为

  • 其他?


您可以使用< input type =tel/> 将输入限制为iOS中的数字 - 尽管这也允许'*'和'#'可以输入,至少它的工作量较少,因为你只需要检查这两个字符


I have an event bound to an input that should only allow numbers. Simplified:

function (e) {
    if (-1 === [48,49,50,51,52,53,54,55,56,57].indexOf(e.keyCode)) {
        e.preventDefault();
    }
}

This works fine, but if someone types !, @, #, $, etc. the keyCode is still the same and the event default is not prevented.

On a physical keyboard, I can prevent this pretty simply by also checking e.shiftKey. However, on an iOS virtual keyboard, some of those characters exist (such as $) even for <input type=number> and they can be typed directly. Their keyCode is the same, but it seems like e.shiftKey is still falsey.

There are a variety of possible solutions that would be acceptable to me:

  • Have the virtual keyboard itself not display these characters (i.e. only display numbers and a period/decimal)
  • Detect that an invalid virtual key was pressed and suppress the event behavior
  • Determine the an invalid character will be added to the input's value and suppress the event behavior in this case
  • Others?

解决方案

you can use <input type="tel" /> to limit the input to numbers in iOS -- although this also allows '*' and '#' to be typed, at least it's less work since you'd only have to check for those two characters

这篇关于Keydown允许数字,但不能在iPhone上移动符号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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