背景
原生input元素,当type=number的时候,允许输入数字、小数点、e(表示指数)。当输入10e的时候,去获取值的时候,会渲染不正确。此时会考虑禁用e/E。
实现
思路
监听keypress事件,中文输入法无效。
所以监听input事件,data表示此刻输入值,_lastValue表示上次的值。
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
<input type="number" id='min'>
<script>
min.addEventListener('input', function (e) {
if (e.data === 'e' || e.data === 'E') {
this.value = this._lastValue || "";
} else {
// 此处需考虑中文输入法情况下,shift+EE(多个E)的情况
typeof this.value !== 'undefined' && this.value.length > 0 && (this._lastValue = this.value);
}
});
// 批量设置
// document.querySelectorAll('input[type=number]').forEach(function (item) {
// item.addEventListener('input', function (e) {
// if (e.data === 'e' || e.data === 'E') {
// this.value = this._lastValue || "";
// } else {
// // 此处需考虑中文输入法情况下,shift+EE(多个E)的情况
// typeof this.value !== 'undefined' && this.value.length > 0 && (this._lastValue = this.value);
// }
// });
// });
</script>
</body>
</html>