aboutsummaryrefslogtreecommitdiff
path: root/files/zh-cn/web/html/element/input/number/index.html
blob: ef7aec63237fd9072ad6751a7b66b12d65a5fcc4 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
---
title: <input type="number">
slug: Web/HTML/Element/Input/number
tags:
  - Element
  - Forms
  - HTML
  - HTML forms
  - Input
  - Number
  - 参考
translation_of: Web/HTML/Element/input/number
---
<div>{{HTMLRef}}</div>

<p><code><strong>"number"</strong></code>类型的 {{HTMLElement("input")}} 元素用于让用户输入一个数字。其包括内置验证以拒绝非数字输入。浏览器可能会选择提供步进箭头,让用户可以使用鼠标增加和减少输入的值,或者只需用指尖敲击即可。</p>

<div class="note">
<p><strong>注意:</strong>不支持 <code>"number"</code> 类型的浏览器会改用标准的 <code><a href="/en-US/docs/Web/HTML/Element/input/text">"text"</a></code> 输入框。</p>
</div>

<div id="Basic_example">
<pre class="brush: html">&lt;input id="number" type="number"&gt;
</pre>

<p>{{ EmbedLiveSample('Basic_example', 600, 40) }}</p>
</div>

<table class="properties">
 <tbody>
  <tr>
   <td><strong>{{anch("Value")}}</strong></td>
   <td>表示一个数字的 {{jsxref("Number")}} ,或 空</td>
  </tr>
  <tr>
   <td><strong>事件</strong></td>
   <td>{{event("change")}}{{event("input")}}</td>
  </tr>
  <tr>
   <td><strong>支持的公共属性</strong></td>
   <td>{{htmlattrxref("autocomplete", "input")}}, {{htmlattrxref("list", "input")}}, {{htmlattrxref("placeholder", "input")}}, {{htmlattrxref("readonly", "input")}}</td>
  </tr>
  <tr>
   <td><strong>IDL 属性</strong></td>
   <td><code>list</code>, <code>value</code>, <code>valueAsNumber</code></td>
  </tr>
  <tr>
   <td><strong>方法</strong></td>
   <td>{{domxref("HTMLInputElement.select", "select()")}}, {{domxref("HTMLInputElement.stepUp", "stepUp()")}}, {{domxref("HTMLInputElement.stepDown", "stepDown()")}}</td>
  </tr>
 </tbody>
</table>

<h2 id="值"></h2>

<p>填写到输入框中的数值文字的{{jsxref("Number")}}表示。你可以通过把一个数字放在{{htmlattrxref("value", "input")}} 属性中来设置输入框的默认值,如下:</p>

<pre class="brush: html">&lt;input id="number" type="number" value="42"&gt;</pre>

<p>{{ EmbedLiveSample('值', 600, 40) }}</p>

<h2 id="使用_number_输入框">使用 number 输入框</h2>

<p><code>&lt;input type ="number"&gt;</code>元素可以帮助您在构建用户界面和将数字输入到表单中的逻辑时简化你的工作。 当你使用正确的 type 值 <code>"number"</code> 创建数字输入时,会自动验证你输入的文本是否为数字,通常是一组向上和向下按钮。</p>

<div class="note">
<p><strong>注意:</strong>记住用户可以在幕后修改HTML是至关重要的,因此您的网站不得使用简单的客户端验证来实现任何安全目的。 您必须在服务器端验证所提供的值可能具有任何安全含义的任何事务。</p>
</div>

<p>此外,移动浏览器通过在用户尝试输入值时显示更适合输入数字的特殊键盘,进一步帮助用户体验。 以下屏幕截图来自Firefox for Android:</p>

<p><img alt="" src="https://mdn.mozillademos.org/files/14963/number-keyboard-fxa.png" style="border-style: solid; border-width: 1px; display: block; margin: 0px auto;"></p>

<h3 id="一个简单的_number_输入框">一个简单的 number 输入框</h3>

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

<pre class="brush: html">&lt;label for="ticketNum"&gt;Number of tickets you would like to buy:&lt;/label&gt;
&lt;input id="ticketNum" type="number" name="ticketNum" value="0"&gt;</pre>

<p>{{ EmbedLiveSample('一个简单的_number_输入框', 600, 40) }}</p>

<p>数字输入在为空的时候以及输入单个数字时被认为是有效的,但是否则是无效的。 如果使用{{htmlattrxref("required","input")}}属性,则输入在空时不再被视为有效。</p>

<div class="note">
<p><strong>注:</strong>任何数字都是可接受的值,只要它是<a href="https://html.spec.whatwg.org/multipage/infrastructure.html#valid-floating-point-number">有效的浮点数</a>(即不是 <a href="/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/NaN">NaN</a><a href="/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/Infinity">Infinity</a>)。</p>
</div>

<h3 id="占位符">占位符</h3>

<p>有时,提供一个如何输入表单数据的上下文提示是非常友好的。尤其当页面所有{{HTMLElement("input")}}  元素都没有说明标签时,会非常重要。这就是使用<strong>占位符</strong>的原因。占位符是一个通常用于说明一个输入框的 <code>value</code> 应该如何输入的提示值,当元素的 <code>value</code> 为  <code>""</code> 时,该提示将出现在编辑框里面。 一旦有数据输入到编辑框中,占位符就会消失;如果该框被清空,占位符将重新出现。</p>

<p>这里,我们有一个占位符为"Multiple of 10"的<code>"number"</code> 输入框。请注意当你在编辑字段内容时占位符是如何消失的又是如何重现的。</p>

<pre class="brush: html">&lt;input type="number" placeholder="Multiple of 10"&gt;</pre>

<p>{{ EmbedLiveSample('占位符', 600, 40) }}</p>

<h3 id="控制步进大小">控制步进大小</h3>

<p>默认情况下,向上和向下按钮可以将值增加或减小1。您可以通过使用{{htmlattrxref("step","input")}} 属性来更改此步长值。 我们上面的例子中的占位符提示我们其值是10的倍数,所以设置 <code>step</code> 的值为10是合理的:</p>

<pre class="brush: html">&lt;input type="number" placeholder="multiple of 10" step="10"&gt;</pre>

<p>{{ EmbedLiveSample('控制步进大小', 600, 40) }}</p>

<p>在这个例子中,你会发现上下箭头每次会将其值增加和减少10,而不是1。你仍然可以手动输入一个不是10的倍数的数字,但它会被认为是无效的。</p>

<h3 id="指定最小和最大值">指定最小和最大值</h3>

<p>可以使用{{htmlattrxref("min","input")}}{{htmlattrxref("max","input")}} 属性指定该字段可以具有的最小值和最大值。 例如,给例子指定最小值为0,最大值为100:</p>

<pre class="brush: html">&lt;input type="number" placeholder="multiple of 10" step="10" min="0" max="100"&gt;</pre>

<p>{{ EmbedLiveSample('指定最小和最大值', 600, 40) }}</p>

<p>修改过后,你会发现点击上下按钮不会让你低于0或高于100 . 可以在这些界限之外手动输入数字,但它将被视为无效。</p>

<h3 id="允许小数值">允许小数值</h3>

<p>数字输入的一个问题是,步长默认为1——如果你尝试输入带小数的数字,例如"1.0",则它将被视为无效。 如果要输入一个需要小数的值,则需要修改 <code>step</code> 值(例如,<code>step="0.01"</code> 以允许2位小数)。 这里有一个简单的例子:</p>

<pre class="brush: html">&lt;input type="number" placeholder="1.0" step="0.01" min="0" max="10"&gt;</pre>

<p>{{EmbedLiveSample("允许小数值", 600, 40)}}</p>

<p>你可以看到这个例子允许0.0到10.0之间的任何值,小数点为2位。本例中,"9.52" 是有效的,但" 9.521" 无效。</p>

<h3 id="控制输入框大小">控制输入框大小</h3>

<p>类型为<code>"number"</code> 的 {{HTMLElement("input")}} 元素不支持像 {{htmlattrxref("size", "input")}} 之类的调整大小属性。你必须通过借助 <a href="/en-US/docs/Web/CSS">CSS</a> 来改变它们的尺寸大小。</p>

<p>例如,要调整输入框的宽度为仅可输入3位数字的宽度,我们可以在HTML中添加 一个ID并缩短很长的占位符文本,如下:</p>

<pre class="brush: html">&lt;input type="number" placeholder="x10" step="10" min="0" max="100" id="number"&gt;</pre>

<p>然后我们添加一些 CSS 来缩小 id 为 <code>"number"</code> 的元素的宽度:</p>

<pre class="brush: css">#number {
  width: 3em;
}</pre>

<p>效果如下:</p>

<p>{{ EmbedLiveSample('控制输入框大小', 600, 40) }}</p>

<h3 id="提供建议值">提供建议值</h3>

<p>You can provide a list of default options from which the user can select by specifying the {{htmlattrxref("list", "input")}} attribute, which contains as its value the ID of a {{HTMLElement("datalist")}}, which in turn contains one {{HTMLElement("option")}} element per suggested value; each <code>option</code>'s <code>value</code> is the corresponding suggested value for the number entry box.</p>

<pre class="brush: html">&lt;input id="ticketNum" type="number" name="ticketNum" list="defaultNumbers"&gt;
&lt;span class="validity"&gt;&lt;/span&gt;

&lt;datalist id="defaultNumbers"&gt;
  &lt;option value="10045678"&gt;
  &lt;option value="103421"&gt;
  &lt;option value="11111111"&gt;
  &lt;option value="12345678"&gt;
  &lt;option value="12999922"&gt;
&lt;/datalist&gt;</pre>

<p>{{EmbedLiveSample("提供建议值", 600, 40)}}</p>

<div class="note">
<p>并非所有浏览器都支持<code>"number"</code> 输入框的 {{htmlattrxref("list", "input")}} 属性。它在 Chrome 和 Opera 中有效,但在 Firefox 中无效。</p>
</div>

<h2 id="验证">验证</h2>

<p>We have alread mentioned a number of validation features of number inputs, but let's review them now:</p>

<ul>
 <li><code>&lt;input type="number"&gt;</code> elements automatically invalidate any entry that isn't a number (or empty, unless <code>required</code> is specified).</li>
 <li>You can use the {{htmlattrxref("required", "input")}} attribute to make an empty entry invalid, i.e. the input has to be filled in.</li>
 <li>You can use the {{htmlattrxref("step", "input")}} attribute to constrain valid values to a certain set of steps (e.g. multiples of 10).</li>
 <li>You can use the {{htmlattrxref("min", "input")}} and {{htmlattrxref("max", "input")}} attributes to constrain valid values to lower and upper bounds.</li>
</ul>

<p>The following example exhibits all of the above features, as well as using some CSS to display valid and invalid icons when the input value is valid/invalid:</p>

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

<p>{{EmbedLiveSample("验证", 600, 80)}}</p>

<p>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.</p>

<p>The CSS applied to this example is as follows:</p>

<pre class="brush: css">div {
  margin-bottom: 10px;
}

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

input:valid+span:after {
  content: '✓';
  padding-left: 5px;
}</pre>

<p>Here we use the {{cssxref(":invalid")}} and {{cssxref(":valid")}} pseudo classes to display an appropriate invalid or valid icon as generated content on the adjacent {{htmlelement("span")}} element, indicating if the current value is valid. We put it on a separate <code>&lt;span&gt;</code> 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 <a href="/en-US/docs/Web/HTML/Element/input/date#Validation"><code>&lt;input type="date"&gt;</code> validation</a>).</p>

<div class="warning">
<p><strong>Important</strong>: HTML form validation is <em>not</em> a substitute for server-side scripts that ensure that the entered data is in the proper format.  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).</p>
</div>

<h3 id="验证模式">验证模式</h3>

<p><code>&lt;input type="number"&gt;</code> elements do not support use of the {{htmlattrxref("pattern", "input")}} attribute for making entered values conform to a specific regex pattern. The rationale for this is that number inputs can't contain anything except numbers, and you can constrain the minimum and maximum number of valid digits using the {{htmlattrxref("min", "input")}} and {{htmlattrxref("max", "input")}} attributes, as explained above.</p>

<h2 id="示例">示例</h2>

<p>We've already covered the fact that by default, the increment is 1, and you can use the {{htmlattrxref("step", "input")}} attribute to allow decimal inputs. Let's take a closer look. In the following example we've set up 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.</p>

<p>{{EmbedLiveSample("示例", 600, 100)}}</p>

<p>The HTML looks like this:</p>

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

<p>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 <code>step</code> value to <code>0.01</code>, so that values like 1.78 are not seen as invalid. We've also provided a placeholder for that input.</p>

<p>We've hidden the feet and inches inputs initially using <code>style="display: none;"</code> so that meters is the default entry type.</p>

<p>Now on to the CSS — this looks very similar to the validation styling we saw before; nothing remarkable here:</p>

<pre class="brush: 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;
}</pre>

<p>And finally, the JavaScript:</p>

<pre class="brush: js">var metersInputGroup = document.querySelector('.metersInputGroup');
var feetInputGroup = document.querySelector('.feetInputGroup');
var metersInput = document.querySelector('#meters');
var feetInput = document.querySelector('#feet');
var inchesInput = document.querySelector('#inches');
var switchBtn = document.querySelector('input[type="button"]');

switchBtn.addEventListener('click', function() {
  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 = '';
  }
});</pre>

<p>After declaring a few variables, we add an event listener to the button to control the switching mechanism. This is pretty simple, mostly involving changing over the button class and label, and updating the display values of the two sets of inputs when the button is pressed. Note that we're not converting back and forth between meters and feet/inches here, which a real-life web application would probably do.</p>

<div class="note">
<p>Note that when the user clicks the button, we remove the <code>required</code> attribute(s) from the input(s) we are hiding, and empty the <code>value</code> attribute(s). This is so that we can submit the form if both input sets aren't filled in, and won't submit data that we didn't mean to submit. If we didn't do this, you'd have to fill in both feet/inches <strong>and</strong> meters to submit the form!</p>
</div>

<h2 id="规范">规范</h2>

<table class="standard-table">
 <thead>
  <tr>
   <th scope="col">Specification</th>
   <th scope="col">Status</th>
   <th scope="col">Comment</th>
  </tr>
 </thead>
 <tbody>
  <tr>
   <td>{{SpecName('HTML WHATWG', 'forms.html#number-state-(type=number)', '&lt;input type="number"&gt;')}}</td>
   <td>{{Spec2('HTML WHATWG')}}</td>
   <td>Initial definition</td>
  </tr>
  <tr>
   <td>{{SpecName('HTML5.1', 'sec-forms.html#number-state-typenumber', '&lt;input type="number"&gt;')}}</td>
   <td>{{Spec2('HTML5.1')}}</td>
   <td>Initial definition</td>
  </tr>
 </tbody>
</table>

<h2 id="浏览器兼容性">浏览器兼容性</h2>

<p>{{CompatibilityTable}}</p>

<div id="compat-desktop">
<table class="compat-table">
 <tbody>
  <tr>
   <th>Feature</th>
   <th>Chrome</th>
   <th>Edge</th>
   <th>Firefox (Gecko)</th>
   <th>Internet Explorer</th>
   <th>Opera</th>
   <th>Safari</th>
  </tr>
  <tr>
   <td>Basic support</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>10</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatVersionUnknown}}</td>
  </tr>
 </tbody>
</table>
</div>

<div id="compat-mobile">
<table class="compat-table">
 <tbody>
  <tr>
   <th>Feature</th>
   <th>Android</th>
   <th>Chrome for Android</th>
   <th>Edge</th>
   <th>Firefox Mobile (Gecko)</th>
   <th>IE Mobile</th>
   <th>Opera Mobile</th>
   <th>iOS WebKit<br>
    <sup><sub>(Safari/Chrome/Firefox/etc.)</sub></sup></th>
  </tr>
  <tr>
   <td>Basic support</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatUnknown}}</td>
   <td>{{CompatVersionUnknown}}</td>
   <td>{{CompatVersionUnknown}}</td>
  </tr>
 </tbody>
</table>
</div>

<h2 id="相关链接">相关链接</h2>

<ul>
 <li><a href="/en-US/docs/Learn/HTML/Forms">HTML forms guide</a></li>
 <li>{{HTMLElement("input")}}</li>
 <li><code><a href="/en-US/docs/Web/HTML/Element/input/tel">&lt;input type="tel"&gt;</a></code></li>
</ul>