HTML5 中是否有浮动输入类型? [英] Is there a float input type in HTML5?
问题描述
根据html5.org,数字"输入类型的值"属性,如果指定并且不为空,必须有一个有效浮点数的值."
According to html5.org, the "number" input type's "value attribute, if specified and not empty, must have a value that is a valid floating point number."
然而它只是(无论如何在最新版本的 Chrome 中),一个带有整数的上下"控件,而不是浮点数:
Yet it is simply (in the latest version of Chrome, anyway), an "updown" control with integers, not floats:
<input type="number" id="totalAmt"></input>
是否有 HTML5 原生的浮点输入元素,或者有一种方法可以使数字输入类型与浮点数一起使用,而不是整数?还是我必须求助于 jQuery UI 插件?
Is there a floating point input element native to HTML5, or a way to make the number input type work with floats, not ints? Or must I resort to a jQuery UI plugin?
推荐答案
number
类型有一个 step
值控制哪些数字是有效的(连同 max
和 min
),默认为 1
.步进按钮的实现也使用此值(即向上按 step
增加).
The number
type has a step
value controlling which numbers are valid (along with max
and min
), which defaults to 1
. This value is also used by implementations for the stepper buttons (i.e. pressing up increases by step
).
只需将此值更改为适当的值即可.对于金钱,可能需要两位小数:
Simply change this value to whatever is appropriate. For money, two decimal places are probably expected:
<input type="number" step="0.01">
(如果它只能是正数,我也会设置 min=0
)
(I'd also set min=0
if it can only be positive)
如果您希望允许任意数量的小数位,您可以使用 step="any"
(但对于货币,我建议坚持使用 0.01
).在 Chrome &在 Firefox 中,使用 any
时,步进按钮将增加/减少 1.(感谢 Michal Stefanow 指出 any
和 在此处查看相关规范)
If you'd prefer to allow any number of decimal places, you can use step="any"
(though for currencies, I'd recommend sticking to 0.01
). In Chrome & Firefox, the stepper buttons will increment / decrement by 1 when using any
. (thanks to Michal Stefanow's answer for pointing out any
, and see the relevant spec here)
这是一个操场,展示了各种步骤如何影响各种输入类型:
Here's a playground showing how various steps affect various input types:
<form>
<input type=number step=1 /> Step 1 (default)<br />
<input type=number step=0.01 /> Step 0.01<br />
<input type=number step=any /> Step any<br />
<input type=range step=20 /> Step 20<br />
<input type=datetime-local step=60 /> Step 60 (default)<br />
<input type=datetime-local step=1 /> Step 1<br />
<input type=datetime-local step=any /> Step any<br />
<input type=datetime-local step=0.001 /> Step 0.001<br />
<input type=datetime-local step=3600 /> Step 3600 (1 hour)<br />
<input type=datetime-local step=86400 /> Step 86400 (1 day)<br />
<input type=datetime-local step=70 /> Step 70 (1 min, 10 sec)<br />
</form>
像往常一样,我会添加一个简短的说明:请记住,客户端验证只是为了方便用户.您还必须在服务器端进行验证!
As usual, I'll add a quick note: remember that client-side validation is just a convenience to the user. You must also validate on the server-side!
这篇关于HTML5 中是否有浮动输入类型?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!