如何使 HTML5 数字字段显示尾随零?
我有一个字段:
<input type='number' />
我想在 0.50
没有更正"到 0.5
的情况下打孔,所以它会显示 0.50
.
I'd like to punch in 0.50
without it "correcting it" to 0.5
, so it would display 0.50
.
推荐答案
我对此进行了一些尝试,并查看了规范.它说它必须是一个有效的浮点数.定义有效浮点数中有一句话它给出的数字引起了我的注意:
I've had a little play around with this and looked at the spec. It says that it must be a valid floating point number. There's one sentence in the definition of a valid floating point number it gives which caught my attention:
数字 n 作为浮点数的最佳表示是通过应用 JavaScript 运算符 ToString 获得的字符串n.
The best representation of the number n as a floating point number is the string obtained from applying the JavaScript operator ToString to n.
这意味着格式将始终与评估数字是一致的,然后在该数字上使用 JavaScript 的 toString.所以没有尾随的 0.
This means that the format will always be consistent with assessing what the number is, then using JavaScript's toString on that number. So no trailing 0s then.
因此,您将不得不求助于 JavaScript.这并不简单,因为 document.getElementById('numInput').value = '0.50';
仍然被更正为 0.5
,所以验证不会在 onchange
可以阻止默认操作的地方,它是在内部触发的.
So, you're going to have to resort to JavaScript. This isn't straightforward because document.getElementById('numInput').value = '0.50';
still gets corrected to 0.5
, so the validation isn't triggered at onchange
where the default action can be prevented, it's triggered internally.
这是我能想到的最好的解决方案......它有点小技巧,需要进行一些调整以提高稳健性,但希望它能满足您的需求:
This is the best solution I could come up with... it's a bit of a hack, and will need a bit of tweaking for robustness, but hopefully it'll do what you want:
var numInput = document.getElementById('numInput');
numInput.addEventListener('keypress', function () {
this.setAttribute('type', 'text');
});
numInput.addEventListener('click', function () {
this.setAttribute('type', 'number');
});
因此,如果用户想通过键入来输入数字,它会将输入类型切换为文本,但当他们单击它时,它会将其转换回数字.
So if the user wants to enter the number by typing, it switches the input type to text, but when they click it, it converts it back to a number.
如果无论用户键入什么内容,您总是想要尾随的 0,那么您可以这样做:
If you always want the trailing 0s no matter what the user types, then you could do it something like this:
var numInput = document.getElementById('numInput');
numInput.addEventListener('blur', function () {
if (this.value === '') {
return;
}
this.setAttribute('type', 'text');
if (this.value.indexOf('.') === -1) {
this.value = this.value + '.00';
}
while (this.value.indexOf('.') > this.value.length - 3) {
this.value = this.value + '0';
}
});
numInput.addEventListener('focus', function () {
this.setAttribute('type', 'number');
});
我认为第二种解决方案更符合用户的期望,但这意味着如果用户输入 0.5
它将被强制为 0.50
,所以这取决于你是否想要.
I think the second solution is more inline with what the user might expect, but it means that if the user types 0.5
it will be coerced to 0.50
, so it depends if that's what you want.
相关文章