HTML5 中有浮点输入类型吗? [英] Is there a float input type in HTML5?

查看:34
本文介绍了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 中,无论如何),一个带有整数的updown"控件,而不是浮点数:

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 值控制哪些数字是有效的(以及 maxmin),默认为 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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆