<input type="number">

number 类型的 <input> 元素用于让用户输入数字。它们包括内置验证以拒绝非数字条目。

¥<input> elements of type number are used to let the user enter a number. They include built-in validation to reject non-numerical entries.

浏览器可能选择提供步进箭头,以便用户使用鼠标或用指尖点击来增加和减少值。

¥The browser may opt to provide stepper arrows to let the user increase and decrease the value using their mouse or by tapping with a fingertip.

Try it

在不支持 number 类型输入的浏览器上,number 输入将回退到 text 类型。

¥On browsers that don't support inputs of type number, a number input falls back to type text.

¥Value

一个数字,表示输入到输入中的数字的值。你可以通过在 value 属性中包含一个数字来设置输入的默认值,如下所示:

¥A number representing the value of the number entered into the input. You can set a default value for the input by including a number inside the value attribute, like so:

html
<input id="number" type="number" value="42" />

附加属性

¥Additional attributes

除了所有 <input> 类型通常支持的属性之外,类型 number 的输入还支持这些属性。

¥In addition to the attributes commonly supported by all <input> types, inputs of type number support these attributes.

list

列表属性的值是位于同一文档中的 <datalist> 元素的 id<datalist> 提供了一个预定义值列表来建议用户进行此输入。列表中与 type 不兼容的任何值都不包含在建议选项中。提供的值是建议,而不是要求:用户可以从此预定义列表中进行选择或提供不同的值。

¥The values of the list attribute is the id of a <datalist> element located in the same document. The <datalist> provides a list of predefined values to suggest to the user for this input. Any values in the list that are not compatible with the type are not included in the suggested options. The values provided are suggestions, not requirements: users can select from this predefined list or provide a different value.

max

此输入接受的最大值。如果输入到元素中的 value 超过此值,则该元素将失败 约束验证。如果 max 属性的值不是数字,则该元素没有最大值。

¥The maximum value to accept for this input. If the value entered into the element exceeds this, the element fails constraint validation. If the value of the max attribute isn't a number, then the element has no maximum value.

该值必须大于或等于 min 属性的值。

¥This value must be greater than or equal to the value of the min attribute.

min

此输入接受的最小值。如果元素的 value 小于此值,则该元素未通过 约束验证。如果为 min 指定的值不是有效数字,则输入没有最小值。

¥The minimum value to accept for this input. If the value of the element is less than this, the element fails constraint validation. If a value is specified for min that isn't a valid number, the input has no minimum value.

该值必须小于或等于 max 属性的值。

¥This value must be less than or equal to the value of the max attribute.

placeholder

placeholder 属性是一个字符串,向用户提供有关该字段中期望的信息类型的简短提示。它应该是一个单词或短语,展示预期的数据类型,而不是解释性消息。文本不得包含回车或换行。

¥The placeholder attribute is a string that provides a brief hint to the user as to what kind of information is expected in the field. It should be a word or short phrase that demonstrates the expected type of data, rather than an explanatory message. The text must not include carriage returns or line feeds.

如果控件的内容具有一个方向性(LTRRTL),但需要以相反的方向性呈现占位符,则可以使用 Unicode 双向算法格式化字符来覆盖占位符内的方向性;请参阅 如何使用 Bidi 文本的 Unicode 控件 了解更多信息。

¥If the control's content has one directionality (LTR or RTL) but needs to present the placeholder in the opposite directionality, you can use Unicode bidirectional algorithm formatting characters to override directionality within the placeholder; see How to use Unicode controls for bidi text for more information.

注意:如果可以的话,请避免使用 placeholder 属性。它在语义上不如解释表单的其他方法那么有用,并且可能会导致内容出现意外的技术问题。请参阅 <input> 标签 了解更多信息。

¥Note: Avoid using the placeholder attribute if you can. It is not as semantically useful as other ways to explain your form, and can cause unexpected technical issues with your content. See <input> labels for more information.

readonly

布尔属性,如果存在,则意味着用户无法编辑该字段。然而,它的 value 仍然可以通过 JavaScript 代码直接设置 HTMLInputElement value 属性来更改。

¥A Boolean attribute which, if present, means this field cannot be edited by the user. Its value can, however, still be changed by JavaScript code directly setting the HTMLInputElement value property.

注意:由于只读字段不能有值,因此 required 对同时指定了 readonly 属性的输入没有任何影响。

¥Note: Because a read-only field cannot have a value, required does not have any effect on inputs with the readonly attribute also specified.

step

step 属性是一个数字,指定值必须遵守的粒度,或者是特殊值 any,如下所述。只有等于步进基础的值(如果指定则为 min,否则为 value,如果未提供则为适当的默认值)才有效。

¥The step attribute is a number that specifies the granularity that the value must adhere to, or the special value any, which is described below. Only values which are equal to the basis for stepping (min if specified, value otherwise, and an appropriate default value if neither of those is provided) are valid.

字符串值 any 意味着不暗示任何步进,并且允许任何值(除非其他约束,例如 minmax)。

¥A string value of any means that no stepping is implied, and any value is allowed (barring other constraints, such as min and max).

注意:当用户输入的数据不符合步进配置时,user agent 可能会四舍五入到最接近的有效值,当有两个同样接近的选项时,优先选择正方向的数字。

¥Note: When the data entered by the user doesn't adhere to the stepping configuration, the user agent may round to the nearest valid value, preferring numbers in the positive direction when there are two equally close options.

number 输入的默认步进值为 1,仅允许输入整数 — 除非步进基数不是整数。

¥The default stepping value for number inputs is 1, allowing only integers to be entered—unless the stepping base is not an integer.

使用数字输入

¥Using number inputs

number 输入类型只能用于增量数字,特别是当旋转按钮递增和递减有助于用户体验时。number 输入类型不适合仅包含数字但严格来说不是数字的值,例如许多国家/地区的邮政编码或信用卡号码。对于非数字输入,请考虑使用不同的输入类型,例如 <input type="tel"> 或其他具有 inputmode 属性的 <input> 类型:

¥The number input type should only be used for incremental numbers, especially when spinbutton incrementing and decrementing are helpful to user experience. The number input type is not appropriate for values that happen to only consist of numbers but aren't strictly speaking a number, such as postal codes in many countries or credit card numbers. For non-numeric inputs, consider using a different input type, such as <input type="tel"> or other <input> type with the inputmode attribute:

html
<input type="text" inputmode="numeric" pattern="\d*" />

<input type="number"> 元素可以帮助简化你构建用于在表单中输入数字的用户界面和逻辑时的工作。当你使用正确的 typenumber 创建数字输入时,你会自动验证输入的文本是否为数字,并且通常会使用一组向上和向下按钮来向上和向下步进值。

¥<input type="number"> elements can help simplify your work when building the user interface and logic for entering numbers into a form. When you create a number input with the proper type value, number, you get automatic validation that the entered text is a number, and usually a set of up and down buttons to step the value up and down.

警告:从逻辑上讲,你不应该能够在数字输入中输入除数字之外的字符。有些浏览器允许无效字符,有些则不允许;见 火狐错误 1398528

¥Warning: Logically, you should not be able to enter characters inside a number input other than numbers. Some browsers allow invalid characters, others do not; see Firefox bug 1398528.

注意:用户可以在幕后修改你的 HTML,因此你的网站不得出于任何安全目的使用简单的客户端验证。你必须在服务器端验证所提供的值可能具有任何类型的安全隐患的任何事务。

¥Note: A user can tinker with your HTML behind the scenes, so your site must not use simple client-side validation for any security purposes. You must verify on the server side any transaction in which the provided value may have security implications of any kind.

当用户尝试输入值时,移动浏览器会显示更适合输入数字的特殊键盘,从而进一步改善用户体验。

¥Mobile browsers further help with the user experience by showing a special keyboard more suited for entering numbers when the user tries to enter a value.

简单的数字输入

¥A simple number input

在最基本的形式中,数字输入可以这样实现:

¥In its most basic form, a number input can be implemented like this:

html
<label for="ticketNum">Number of tickets you would like to buy:</label>
<input id="ticketNum" type="number" name="ticketNum" value="0" />

当为空且输入单个数字时,数字输入被视为有效,否则无效。如果使用 required 属性,则输入为空时不再被视为有效。

¥A number input is considered valid when empty and when a single number is entered, but is otherwise invalid. If the required attribute is used, the input is no longer considered valid when empty.

注意:任何数字都是可接受的值,只要它是 有效的浮点数(即不是 NaN无穷)即可。

¥Note: Any number is an acceptable value, as long as it is a valid floating point number (that is, not NaN or Infinity).

占位符

¥Placeholders

有时,提供有关输入数据应采用什么形式的上下文提示会很有帮助。如果页面设计没有为每个 <input> 提供描述性标签,这一点尤其重要。这就是占位符发挥作用的地方。占位符是最常用于提供输入应采用 value 格式的提示的值。当元素的 value"" 时,它会显示在编辑框中。一旦数据输入到框中,占位符就会消失;如果该框被清空,则占位符会重新出现。

¥Sometimes it's helpful to offer an in-context hint as to what form the input data should take. This can be especially important if the page design doesn't offer descriptive labels for each <input>. This is where placeholders come in. A placeholder is a value most commonly used to provide a hint as to the format the input should take value. It is displayed inside the edit box when the element's value is "". Once data is entered into the box, the placeholder disappears; if the box is emptied, the placeholder reappears.

在这里,我们有一个带有占位符“Multiple of 10”的 number 输入。请注意当你操作编辑字段的内容时占位符如何消失和重新出现。

¥Here, we have an number input with the placeholder "Multiple of 10". Note how the placeholder disappears and reappears as you manipulate the contents of the edit field.

html
<input type="number" placeholder="Multiple of 10" />

控制步长

¥Controlling step size

默认情况下,为你提供的向上和向下步进数字的按钮会将值向上和向下步进 1。你可以通过提供 step 属性来更改此设置,该属性将指定步数的数字作为其值。上面的示例包含一个占位符,表示该值应该是 10 的倍数,因此将 step 值添加到 10 是有意义的:

¥By default, the up and down buttons provided for you to step the number up and down will step the value up and down by 1. You can change this by providing a step attribute, which takes as its value a number specifying the step amount. Our above example contains a placeholder saying that the value should be a multiple of 10, so it makes sense to add a step value of 10:

html
<input type="number" placeholder="multiple of 10" step="10" />

在此示例中,你应该发现向上和向下步进箭头每次都会将值增加和减少 10,而不是 1。你仍然可以手动输入不是 10 倍数的数字,但该数字将被视为无效。

¥In this example, you should find that the up and down step arrows will increase and decrease the value by 10 each time, not 1. You can still manually enter a number that's not a multiple of 10, but it will be considered invalid.

指定最小值和最大值

¥Specifying minimum and maximum values

你可以使用 minmax 属性来指定字段可以具有的最小值和最大值。例如,让我们的示例的最小值为 0,最大值为 100

¥You can use the min and max attributes to specify a minimum and maximum value that the field can have. For example, let's give our example a minimum of 0, and a maximum of 100:

html
<input type="number" placeholder="multiple of 10" step="10" min="0" max="100" />

在此更新版本中,你应该会发现向上和向下步进按钮不允许你低于 0 或高于 100。你仍然可以手动输入这些范围之外的数字,但该数字将被视为无效。

¥In this updated version, you should find that the up and down step buttons will not allow you to go below 0 or above 100. You can still manually enter a number outside these bounds, but it will be considered invalid.

允许小数值

¥Allowing decimal values

数字输入的一个问题是它们的步长默认为 1。如果你尝试输入带小数的数字(例如 "1.0"),将被视为无效。如果要输入需要小数的值,则需要在 step 值中反映这一点(例如 step="0.01" 允许小数点到小数点后两位)。这是一个简单的例子:

¥One issue with number inputs is that their step size is 1 by default. If you try to enter a number with a decimal (such as "1.0"), it will be considered invalid. If you want to enter a value that requires decimals, you'll need to reflect this in the step value (e.g. step="0.01" to allow decimals to two decimal places). Here's a simple example:

html
<input type="number" placeholder="1.0" step="0.01" min="0" max="10" />

请注意,此示例允许 0.010.0 之间的任何值,并且小数点到两位。例如,"9.52" 有效,但 "9.521" 无效。

¥See that this example allows any value between 0.0 and 10.0, with decimals to two places. For example, "9.52" is valid, but "9.521" is not.

控制输入大小

¥Controlling input size

number 类型的 <input> 元素不支持表单大小调整属性,例如 size。你必须求助于 CSS 来更改这些控件的大小。

¥<input> elements of type number don't support form sizing attributes such as size. You'll have to resort to CSS to change the size of these controls.

例如,要将输入的宽度调整为输入三位数所需的宽度,我们可以更改 HTML 以包含 id 并缩短占位符,因为该字段对于文本来说太窄 到目前为止我们一直在使用:

¥For example, to adjust the width of the input to be only as wide as is needed to enter a three-digit number, we can change our HTML to include an id and to shorten our placeholder since the field will be too narrow for the text we have been using so far:

html
<input
  type="number"
  placeholder="x10"
  step="10"
  min="0"
  max="100"
  id="number" />

然后我们添加一些 CSS 以使用 id 选择器 #number 缩小元素的宽度:

¥Then we add some CSS to narrow the width of the element with the id selector #number:

css
#number {
  width: 3em;
}

结果如下:

¥The result looks like this:

提供建议值

¥Offering suggested values

你可以提供一个默认选项列表,用户可以通过指定 list 属性从中进行选择,该属性包含 <datalist>id 作为其值,而 <datalist> 又包含每个建议值一个 <option> 元素。每个 optionvalue 是数字输入框对应的建议值。

¥You can provide a list of default options from which the user can select by specifying the list attribute, which contains as its value the id of a <datalist>, which in turn contains one <option> element per suggested value. Each option's value is the corresponding suggested value for the number entry box.

html
<input id="ticketNum" type="number" name="ticketNum" list="defaultNumbers" />
<span class="validity"></span>

<datalist id="defaultNumbers">
  <option value="10045678"></option>
  <option value="103421"></option>
  <option value="11111111"></option>
  <option value="12345678"></option>
  <option value="12999922"></option>
</datalist>

验证

¥Validation

我们已经提到了 number 输入的许多验证功能,但现在让我们回顾一下它们:

¥We have already mentioned a number of validation features of number inputs, but let's review them now:

  • <input type="number"> 元素会自动使任何非数字(或空,除非指定 required)的条目无效。
  • 你可以使用 required 属性使空条目无效。(换句话说,必须填写输入内容。)
  • 你可以使用 step 属性将有效值限制为一组特定的步骤(例如 10 的倍数)。
  • 你可以使用 minmax 属性将有效值限制为下限和上限。

以下示例展示了上述所有功能,并使用一些 CSS 来显示有效和无效图标,具体取决于 input 的值:

¥The following example exhibits all of the above features, as well as using some CSS to display valid and invalid icons, depending on the input's value:

html
<form>
  <div>
    <label for="balloons">Number of balloons to order (multiples of 10):</label>
    <input
      id="balloons"
      type="number"
      name="balloons"
      step="10"
      min="0"
      max="100"
      required />
    <span class="validity"></span>
  </div>
  <div>
    <input type="submit" />
  </div>
</form>

尝试提交输入了不同无效值的表单 - 例如,没有值;低于 0 或高于 100 的值;不是 10 的倍数的值;或非数字值 - 看看浏览器给你的错误消息在不同的情况下有何不同。

¥Try submitting the form with different invalid values entered — e.g., no value; a value below 0 or above 100; a value that is not a multiple of 10; or a non-numerical value — and see how the error messages the browser gives you differ with different ones.

本例应用的 CSS 如下:

¥The CSS applied to this example is as follows:

css
div {
  margin-bottom: 10px;
}

input:invalid + span::after {
  content: "✖";
  padding-left: 5px;
}

input:valid + span::after {
  content: "✓";
  padding-left: 5px;
}

在这里,我们使用 :invalid:valid 伪类在相邻 <span> 元素上显示适当的无效或有效图标作为生成的内容,作为有效性的视觉指示符。

¥Here we use the :invalid and :valid pseudo classes to display an appropriate invalid or valid icon as generated content on the adjacent <span> element, as a visual indicator of validity.

我们将其放在单独的 <span> 元素上以增加灵活性。某些浏览器无法在某些类型的表单输入上非常有效地显示生成的内容。(例如,阅读有关 <input type="date"> 验证 的部分。)

¥We put it on a separate <span> element for added flexibility. Some browsers don't display generated content very effectively on some types of form inputs. (Read, for example, the section on <input type="date"> validation.)

警告:HTML 表单验证不能替代服务器端脚本,确保输入的数据格式正确!

¥Warning: HTML form validation is not a substitute for server-side scripts that ensure that the entered data is in the proper format!

对于某人来说,对 HTML 进行调整以绕过验证或完全删除它太容易了。其他人也有可能绕过你的 HTML 并将数据直接提交到你的服务器。

¥It's far too easy for someone to make adjustments to the HTML that allow them to bypass the validation, or to remove it entirely. It's also possible for someone to bypass your HTML and submit the data directly to your server.

如果你的服务器端代码无法验证其接收到的数据,则当提交格式不正确的数据(或数据太大、类型错误等)时,可能会发生灾难。

¥If your server-side code fails to validate the data it receives, disaster could strike when improperly-formatted data is submitted (or data which is too large, is of the wrong type, and so forth).

模式验证

¥Pattern validation

<input type="number"> 元素不支持使用 pattern 属性来使输入的值符合特定的正则表达式模式。

¥<input type="number"> elements do not support use of the pattern attribute for making entered values conform to a specific regex pattern.

这样做的理由是,如果数字输入包含除数字之外的任何内容,则它们将无效,并且你可以使用 minmax 属性来限制有效数字的最小和最大数量(如上所述)。

¥The rationale for this is that number inputs won't be valid if they contain anything except numbers, and you can constrain the minimum and maximum number of valid digits using the min and max attributes (as explained above).

示例

¥Examples

我们已经介绍过这样一个事实:默认情况下,增量为 1,你可以使用 step 属性来允许十进制输入。让我们仔细看看。

¥We've already covered the fact that by default, the increment is 1, and you can use the step attribute to allow decimal inputs. Let's take a closer look.

以下示例是用于输入用户身高的表单。它默认接受以米为单位的高度,但你可以单击相关按钮来更改表单以接受英尺和英寸。以米为单位的高度输入接受两位小数。

¥In the following example is a form for entering the user's height. It defaults to accepting a height in meters, but you can click the relevant button to change the form to accept feet and inches instead. The input for the height in meters accepts decimals to two places.

HTML 看起来像这样:

¥The HTML looks like this:

html
<form>
  <div class="metersInputGroup">
    <label for="meters">Enter your height — meters:</label>
    <input
      id="meters"
      type="number"
      name="meters"
      step="0.01"
      min="0"
      placeholder="e.g. 1.78"
      required />
    <span class="validity"></span>
  </div>
  <div class="feetInputGroup" style="display: none;">
    <span>Enter your height — </span>
    <label for="feet">feet:</label>
    <input id="feet" type="number" name="feet" min="0" step="1" />
    <span class="validity"></span>
    <label for="inches">inches:</label>
    <input id="inches" type="number" name="inches" min="0" max="11" step="1" />
    <span class="validity"></span>
  </div>
  <div>
    <input
      type="button"
      class="meters"
      value="Enter height in feet and inches" />
  </div>
  <div>
    <input type="submit" value="Submit form" />
  </div>
</form>

你将看到我们正在使用我们在前面的文章中已经介绍过的许多属性。由于我们想要接受以厘米为单位的米值,因此我们将 step 值设置为 0.01,这样像 1.78 这样的值就不会被视为无效。我们还为该输入提供了一个占位符。

¥You'll see that we are using many of the attributes we've already looked at in the article earlier on. Since we want to accept a meter value in centimeters, we've set the step value to 0.01, so that values like 1.78 are not seen as invalid. We've also provided a placeholder for that input.

我们最初使用 style="display: none;" 隐藏了英尺和英寸输入,因此米是默认输入类型。

¥We've hidden the feet and inches inputs initially using style="display: none;", so that meters is the default entry type.

现在,进入 CSS。这看起来与我们之前看到的验证样式非常相似;这里没什么了不起的。

¥Now, onto the CSS. This looks very similar to the validation styling we saw before; nothing remarkable here.

css
div {
  margin-bottom: 10px;
  position: relative;
}

input[type="number"] {
  width: 100px;
}

input + span {
  padding-right: 30px;
}

input:invalid + span::after {
  position: absolute;
  content: "✖";
  padding-left: 5px;
}

input:valid + span::after {
  position: absolute;
  content: "✓";
  padding-left: 5px;
}

最后是 JavaScript:

¥And finally, the JavaScript:

js
const metersInputGroup = document.querySelector(".metersInputGroup");
const feetInputGroup = document.querySelector(".feetInputGroup");
const metersInput = document.querySelector("#meters");
const feetInput = document.querySelector("#feet");
const inchesInput = document.querySelector("#inches");
const switchBtn = document.querySelector('input[type="button"]');

switchBtn.addEventListener("click", () => {
  if (switchBtn.getAttribute("class") === "meters") {
    switchBtn.setAttribute("class", "feet");
    switchBtn.value = "Enter height in meters";

    metersInputGroup.style.display = "none";
    feetInputGroup.style.display = "block";

    feetInput.setAttribute("required", "");
    inchesInput.setAttribute("required", "");
    metersInput.removeAttribute("required");

    metersInput.value = "";
  } else {
    switchBtn.setAttribute("class", "meters");
    switchBtn.value = "Enter height in feet and inches";

    metersInputGroup.style.display = "block";
    feetInputGroup.style.display = "none";

    feetInput.removeAttribute("required");
    inchesInput.removeAttribute("required");
    metersInput.setAttribute("required", "");

    feetInput.value = "";
    inchesInput.value = "";
  }
});

声明几个变量后,在 button 中添加一个事件监听器来控制切换机制。这很简单,主要涉及更改按钮的 class<label>,以及在按下按钮时更新两组输入的显示值。

¥After declaring a few variables, an event listener is added to the button to control the switching mechanism. This is pretty simple, mostly involving changing over the button's class and <label>, and updating the display values of the two sets of inputs when the button is pressed.

(请注意,我们不会在米和英尺/英寸之间来回转换,而现实生活中的 Web 应用可能会这样做。)

¥(Note that we're not converting back and forth between meters and feet/inches here, which a real-life web application would probably do.)

注意:当用户单击该按钮时,required 属性将从我们隐藏的输入中删除,并清空 value 属性。这样,如果两个输入集均未填写,则可以提交表单。它还确保表单不会提交用户无意的数据。

¥Note: When the user clicks the button, the required attribute(s) are removed from the input(s) we are hiding, and empty the value attribute(s). This is so the form can be submitted if both input sets aren't filled in. It also ensures that the form won't submit data that the user didn't mean to.

如果你不这样做,则必须填写英尺/英寸和米才能提交表格!

¥If you didn't do this, you'd have to fill in both feet/inches and meters to submit the form!

无障碍问题

¥Accessibility concerns

<input type="number"> 元素的隐式 rolespinbutton。如果旋转按钮对于表单控件来说不是一个重要功能,请考虑不使用 type="number"。相反,应将 inputmode="numeric"pattern 属性一起使用,将字符限制为数字和关联字符。对于 <input type="number">,用户在尝试执行其他操作时存在意外增加数字的风险。此外,如果用户尝试输入非数字的内容,则不会有关于他们做错了什么的明确反馈。

¥The implicit role for the <input type="number"> element is spinbutton. If spinbutton is not an important feature for your form control, consider not using type="number". Instead, use inputmode="numeric" along with a pattern attribute that limits the characters to numbers and associated characters. With <input type="number">, there is a risk of users accidentally incrementing a number when they're trying to do something else. Additionally, if users try to enter something that's not a number, there's no explicit feedback about what they're doing wrong.

还可以考虑使用 autocomplete 属性来帮助用户更快地完成表单并减少出错的机会。例如,要在邮政编码字段上启用自动填充,请设置 autocomplete="postal-code"

¥Also consider using the autocomplete attribute to help users complete forms more quickly and with fewer chances of errors. For example, to enable autofill on a zip code field, set autocomplete="postal-code".

技术总结

¥Technical summary

Number 代表数字,或者空
活动 changeinput
支持的通用属性 autocomplete, list, placeholder, readonly
IDL 属性 list, value, valueAsNumber
DOM 接口

HTMLInputElement

方法 select(), stepUp(), stepDown()
隐式 ARIA 角色 spinbutton

规范

Specification
HTML Standard
# number-state-(type=number)

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看