解决方法
我已经玩了一下,看着这个规格。它说它必须是一个有效的浮点数。在
definition of a valid floating point number中有一句话引起了我的注意:
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。
所以,你将不得不诉诸于JavaScript。这不是直接的,因为document.getElementById(‘numInput’)。value =’0.50′;仍然被修正为0.5,所以验证不会在可以防止默认操作的交换处触发,它在内部触发。
这是我可以想出来的最好的解决方案…这是一个黑客,需要一些调整的鲁棒性,但希望它会做你想要的:
var numInput = document.getElementById('numInput'); numInput.addEventListener('keypress',function () { this.setAttribute('type','text'); }); numInput.addEventListener('click','number'); });
所以如果用户想通过键入输入数字,它会将输入类型切换为文本,但是当它们点击它时,它会将其转换回一个数字。
如果您始终希望尾随0,无论用户类型如何,那么您可以这样做:
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','number'); });
编辑:我认为第二个解决方案更符合用户期望的内容,但这意味着,如果用户键入0.5,它将被强制为0.50,所以这取决于这是否是你想要的。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。