我有以下html5输入元素:

<input type="number">

为什么这个输入允许在输入字段中输入字符“e”?无法输入其他字母字符(如预期的那样)

使用chrome v. 44.0.2403.107

下面的例子来看看我的意思。

= >“当家”型输入<


当前回答

<input type="number" onkeydown="javascript: return ['Backspace','Delete','ArrowLeft','ArrowRight'].includes(event.code) ?isNaN(Number(event.key)) && event.code!= =‘空间’" / >

其他回答

强制使用仅由数字组成的数字的最佳方法:

<input type="number" onkeydown="javascript: return ['Backspace','Delete','ArrowLeft','ArrowRight'].includes(event.code) ?isNaN(Number(event.key)) && event.code!= =‘空间’" / >

这避免了'e', '-', '+', '。“…所有不是数字的字符!

若要只允许数字键,请使用数字函数转换为数字。如果不是数字,则结果为NaN:

isNaN(当家(基)事件。

但接受退格,删除,左箭头,右箭头:

[个’,‘删除’‘ArrowLeft’,‘ArrowRight includes(事件。代码)

这是为允许空格的Firefox设置的:

event.code != =“空间”

如果你按下一个键,它的计算机语言相当于69,它就不会输入

<input
 type="number"
 onkeydown="return event.keyCode !== 69"
/>

使用angular,你可以限制输入e,+,-, e

 <input type="number"  (keypress)="numericOnly($event)"/>


  numericOnly(event): boolean { // restrict e,+,-,E characters in  input type number
    debugger
    const charCode = (event.which) ? event.which : event.keyCode;
    if (charCode == 101 || charCode == 69 || charCode == 45 || charCode == 43) {
      return false;
    }
    return true;

  }

要隐藏字母e和负号,可以这样做:

onkeydown="return event.keyCode !== 69 && event.keyCode !== 189"

因为这正是规范所规定的。数字输入可以接受浮点数,包括负号和e或e字符(其中指数是e或e后面的数字):

A floating-point number consists of the following parts, in exactly the following order: Optionally, the first character may be a "-" character. One or more characters in the range "0—9". Optionally, the following parts, in exactly the following order: a "." character one or more characters in the range "0—9" Optionally, the following parts, in exactly the following order: a "e" character or "E" character optionally, a "-" character or "+" character One or more characters in the range "0—9".