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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
|
---
title: <input type="month">
slug: Web/HTML/Element/input/month
tags:
- HTML
- Input
- 表单
translation_of: Web/HTML/Element/input/month
original_slug: Web/HTML/Element/Input/月份
---
<p>{{HTMLRef}}</p>
<p>类型为 <strong><code>month</code></strong> 的 {{htmlelement("input")}} 可以让你容易地创建一个方便输入年份或月份的一个 {{htmlelement("input")}}。</p>
<div>{{EmbedInteractiveExample("pages/tabbed/input-month.html", "tabbed-shorter")}}</div>
<p>这个控件在各个浏览器支持都不同,目前是支持部分浏览器。在桌面上支持情况为 Chrome/Opera 和 Edge 。在移动端支持大部分现代浏览器。在其他浏览器中,这个控件会被优雅的降级到<code><a href="/en-US/docs/Web/HTML/Element/input/text"><input type="text"></a></code>.</p>
<p>对于那些使用不支持的浏览器的用户,Chrome / Opera 月份控制如下图所示。单击右侧的向下箭头会显示日期选择器,以便您选择日期;你必须手动输入时间。</p>
<p><img alt="" src="https://mdn.mozillademos.org/files/15391/month-control-chrome.png" style="display: block; height: 216px; margin: 0px auto; width: 273px;"></p>
<p>Edge 的 <code>month</code> 看起来像这样的:</p>
<p><img alt="" src="https://mdn.mozillademos.org/files/15393/month-control-edge.png" style="display: block; height: 389px; margin: 0px auto; width: 227px;"></p>
<table class="properties">
<tbody>
<tr>
<td><strong>{{anch("Value")}}</strong></td>
<td>一个 {{domxref("DOMString")}} 代表一个月,一年,或者是空。</td>
</tr>
<tr>
<td><strong>Events</strong></td>
<td>{{event("change")}} 和 {{event("input")}}.</td>
</tr>
<tr>
<td><strong>Supported Common Attributes</strong></td>
<td>{{htmlattrxref("autocomplete", "input")}}, {{htmlattrxref("list", "input")}}, {{htmlattrxref("readonly", "input")}}, 和 {{htmlattrxref("step", "input")}}.</td>
</tr>
<tr>
<td><strong>IDL attributes</strong></td>
<td><code>value</code>.</td>
</tr>
<tr>
<td><strong>Methods</strong></td>
<td>{{domxref("HTMLInputElement.select", "select()")}}, {{domxref("HTMLInputElement.stepDown", "stepDown()")}}, {{domxref("HTMLInputElement.stepUp", "stepUp()")}}.</td>
</tr>
</tbody>
</table>
<h2 id="Value">Value</h2>
<p>{{domxref("DOMString")}} 表示输入输入的月份和年份的值,in the form YYYY-MM (four or more digit year, then a hyphen ("<code>-</code>"), followed by the two-digit month). The format of the month string used by this input type is described in {{SectionOnPage("/en-US/docs/Web/HTML/Date_and_time_formats", "Format of a valid local month string")}}.</p>
<p>你可以设置一个默认的属性值插入到 {{htmlattrxref("value", "input")}} 里,像这样:</p>
<pre class="brush: html"><label for="bday-month">What month were you both in?</label>
<input id="bday-month" type="month" name="bday-month" value="2017-06"></pre>
<p>{{EmbedLiveSample('value-example-1', 600, 60)}}</p>
<p>需要注意的是显示的如期格式不同于实际的<code>value</code> — 日期显示的格式将根据用户的操作系统的时区设置,而时间的格式通常会格式化为 <code>yyyy-MM</code>。</p>
<p>在向服务器提交上述值的时候他们看起来像这样:<code>bday-month=1978-06</code>.</p>
<p>你也可以使用 JavaScript 的 {{domxref("HTMLInputElement.value")}} 来设置日期的值 。例如:</p>
<pre class="brush: js">var monthControl = document.querySelector('input[type="month"]');
monthControl.value = '1978-06';</pre>
<p>{{EmbedLiveSample("value-example-2", 600, 60)}}</p>
<p> </p>
<h2 id="Additional_attributes">Additional attributes</h2>
<p>In addition to the attributes common to {{HTMLElement("input")}} elements, month inputs offer the following attributes:</p>
<table class="standard-table">
<thead>
<tr>
<th scope="col">Attribute</th>
<th scope="col">Description</th>
</tr>
</thead>
<tbody>
<tr>
<td><code>{{anch("max")}}</code></td>
<td>The latest year and month to accept as a valid input</td>
</tr>
<tr>
<td><code>{{anch("min")}}</code></td>
<td>The earliest year and month to accept as a valid input</td>
</tr>
<tr>
<td><code>{{anch("readonly")}}</code></td>
<td>A Boolean which, if present, indicates that the input's value can't be edited</td>
</tr>
<tr>
<td><code>{{anch("step")}}</code></td>
<td>A stepping interval to use when incrementing and decrementing the value of the input field</td>
</tr>
</tbody>
</table>
<h3 id="htmlattrdef(max)">{{htmlattrdef("max")}}</h3>
<p>The latest year and month, in the string format discussed in the {{anch("Value")}} section above, to accept. If the {{htmlattrxref("value", "input")}} entered into the element exceeds this, the element fails <a href="https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/HTML5/Constraint_validation">constraint validation</a>. If the value of the <code>max</code> attribute isn't a valid string in "<code>yyyy-MM</code>" format, then the element has no maximum value.</p>
<p>This value must specify a year-month pairing later than or equal to the one specified by the <code>min</code> attribute.</p>
<h3 id="htmlattrdef(min)">{{htmlattrdef("min")}}</h3>
<p>The latest year and month to accept, in the same "<code>yyyy-MM</code>" format described above. If the {{htmlattrxref("value", "input")}} of the element is less than this, the element fails <a href="https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/HTML5/Constraint_validation">constraint validation</a>. If a value is specified for <code>min</code> that isn't a valid year and month string, the input has no minimum value.</p>
<p>This value must be a year-month pairing which is earlier than or equal to the one specified by the <code>max</code> attribute.</p>
<h3 id="htmlattrdef(readonly)">{{htmlattrdef("readonly")}}</h3>
<p>A Boolean attribute which, if present, means this field cannot be edited by the user. Its <code>value</code> can, however, still be changed from JavaScript code that directly sets the value of the {{domxref("HTMLInputElement.value")}} property.</p>
<div class="note">
<p><strong>Note:</strong> Because a read-only field cannot have a value, <code>required</code> does not have any effect on inputs with the <code>readonly</code> attribute also specified.</p>
</div>
<h3 id="htmlattrdef(step)">{{htmlattrdef("step")}}</h3>
<p>{{page("/en-US/docs/Web/HTML/Element/input/number", "step-include")}}</p>
<p>For <code>month</code> inputs, the value of <code>step</code> is given in months, with a scaling factor of 1 (since the underlying numeric value is also in months). The default value of <code>step</code> is 1 month.</p>
<p> </p>
<h2 id="Using_month_inputs">Using month inputs</h2>
<p>与日期相关的输入乍一看很方便,它们提供了一个简单的用户界面来选择日期,并且它们将发送到服务器的数据格式规范化,而不考虑用户的本地环境。但是,由于浏览器支持有限,所以这个 <code><input type="month"></code>还是存在兼容性问题。</p>
<p>我们在往下看更多关于<code><input type="month"></code>基础和更多的高级的用法</p>
<p>, 下面将讲有关缓解浏览器支持问题的建议 (请参阅{{anch("Handling browser support")}}).</p>
<h3 id="Basic_uses_of_month">Basic uses of month</h3>
<p>最简单的<code><input type="month"></code> 涉及到基础的 <code><input></code> 和 {{htmlelement("label")}} 的元素组合,像下面这样:</p>
<pre class="brush: html"><form>
<label for="bday-month">What month were you both in?</label>
<input id="bday-month" type="month" name="bday-month">
</form></pre>
<p>{{ EmbedLiveSample('Basic_uses_of_month', 600, 40) }}</p>
<h3 id="设置最长和最短日期">设置最长和最短日期</h3>
<p>你可以使用{{htmlattrxref("min", "input")}} 和 {{htmlattrxref("max", "input")}} 属性 来限制用户选择日期。在下列的例子中我们设置最小月份<code>1900-01</code> 最大月份到 <code>2017-08</code>:</p>
<pre class="brush: html"><form>
<label for="bday-month">What month were you both in?</label>
<input id="bday-month" type="month" name="bday-month"
min="1900-01" max="2017-08">
</form></pre>
<p>{{ EmbedLiveSample('Setting_maximum_and_minimum_dates', 600, 40) }}</p>
<p>结果是这样:</p>
<ul>
<li>月份只有在 2017 年八月份到 1900 年一月可以选择 — 在这个控件里这个范围以外的月份不能滚动选择。</li>
<li>Depending on what browser you are using, you might find that times outside the specified values might not be selectable in the time picker (e.g. Edge), or invalid (see {{anch("Validation")}}) but still available (e.g. Chrome).</li>
</ul>
<div class="note">
<p><strong>Note</strong>: You should be able to use the {{htmlattrxref("step", "input")}} attribute to vary the number of days jumped each time the date is incremented (e.g. maybe you only want to make Saturdays selectable). However, this does not seem to work effectively in any implementation at the time of writing.</p>
</div>
<h3 id="Controlling_input_size">Controlling input size</h3>
<p><code><input type="month"></code> doesn't support form sizing attributes such as {{htmlattrxref("size", "input")}}. You'll have to resort to <a href="/en-US/docs/Web/CSS">CSS</a> for sizing needs.</p>
<h2 id="Validation">Validation</h2>
<p>By default, <code><input type="month"></code> does not apply any validation to entered values. The UI implementations generally don't let you enter anything that isn't a date — which is helpful — but you can still not fill in a date and submit, or enter an invalid date (e.g. the 32th of April).</p>
<p>You can use {{htmlattrxref("min", "input")}} and {{htmlattrxref("max", "input")}} to restrict the available dates (see anch("Setting maximum and minimum dates")), and in addition use the {{htmlattrxref("required", "input")}} attribute to make filling in the date mandatory. As a result, supporting browsers will display an error if you try to submit a date that is outside the set bounds, or an empty date field.</p>
<p>Let's look at an example — here we've set minimum and maximum dates, and also made the field required:</p>
<pre class="brush: html"><form>
<div>
<label for="month">What Month would you like to visit us? (Summer months only.)</label>
<input id="month" type="month" name="month"
min="2017-06" max="2017-09" required>
<span class="validity"></span>
</div>
<div>
<input type="submit" value="Submit form">
</div>
</form></pre>
<p>If you try to submit the form with an incomplete date (or with a date outside the set bounds), the browser displays an error. Try playing with the example now:</p>
<p>{{ EmbedLiveSample('Validation', 600, 120) }}</p>
<p>Here's'a screenshot for those of you who aren't using a supporting browser:</p>
<p><img alt="" src="https://mdn.mozillademos.org/files/15395/month-required.png" style="display: block; margin: 0 auto;"></p>
<p>Here's the CSS used in the above example. Here we make use of the {{cssxref(":valid")}} and {{cssxref(":invalid")}} CSS properties to style the input based on whether or not the current value is valid. We had to put the icons on a {{htmlelement("span")}} next to the input, not on the input itself, because in Chrome the generated content is placed inside the form control, and can't be styled or shown effectively.</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>
<div class="warning">
<p><strong>Important</strong>: HTML form validation is <em>not</em> a substitute for 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 simply bypass your HTML entirely 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, of the wrong type, and so forth).</p>
</div>
<h2 id="Handling_browser_support">Handling browser support</h2>
<p>As mentioned above, the major problem with using date inputs at the time of writing is browser support — only Chrome/Opera and Edge support it on desktop, and most modern browsers on mobile. As an example, the <code>month</code> picker on Chrome for Android looks like this:</p>
<p><img alt="" src="https://mdn.mozillademos.org/files/15397/month-android.png" style="display: block; margin: 0 auto;"></p>
<p>Non-supporting browsers gracefully degrade to a text input, but this creates problems both in terms of consistency of user interface (the presented control will be different), and data handling.</p>
<p>The second problem is the most serious — as we mentioned earlier, with a <code>month</code> input the actual value is always normalized to the format <code>yyyy-mm</code>. With a text input on the other hand, by default the browser has no recognition of what format the date should be in, and there multiple ways in which people write dates, for example:</p>
<ul>
<li><code>mmyyyy</code></li>
<li><code>mm/yyyy</code></li>
<li><code>mm-yyyy</code></li>
<li><code>yyyy-mm</code></li>
<li>etc.</li>
</ul>
<p>One way around this is to put a {{htmlattrxref("pattern", "input")}} attribute on your <code>month</code> input. Even though the <code>month</code> input doesn't use it, the text input fallback will. For example, try viewing the following demo in a non-supporting browser:</p>
<pre class="brush: html"><form>
<div>
<label for="month">What Month would you like to visit us? (Summer months only, yyyy-mm)</label>
<input id="month" type="month" name="month"
min="2017-06" max="2017-09" required
pattern="[0-9]{4}-[0-9]{2}">
<span class="validity"></span>
</div>
<div>
<input type="submit" value="Submit form">
</div>
</form></pre>
<p>{{ EmbedLiveSample('Handling_browser_support', 600, 100) }}</p>
<p>If you try submitting it, you'll see that the browser now displays an error message (and highlights the input as invalid) if your entry doesn't match the pattern <code>nnnn-nn</code>, where <code>n</code> is a number from 0 to 9. Of course, this doesn't stop people from entering invalid dates, or incorrectly formatted dates that follow the pattern.</p>
<p>And what user is going to understand the pattern they need to enter the date in?</p>
<p>We still have a problem.</p>
<div class="hidden">
<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>
</div>
<p>The best way to deal with dates in forms in a cross-browser way at the moment is to get the user to enter the month and year in separate controls ({{htmlelement("select")}} elements being popular — see below for an implementation), or use JavaScript libraries such as <a href="https://jqueryui.com/datepicker/">jQuery date picker</a>, and the <a href="http://timepicker.co/">jQuery timepicker plugin</a>.</p>
<h2 id="Examples">Examples</h2>
<p>In this example we create two sets of UI elements for choosing dates — a native picker created with <code><input type="month"></code>, and a set of two {{htmlelement("select")}} elements for choosing months/years in older browsers that don't support the native input.</p>
<p>{{ EmbedLiveSample('Examples', 600, 140) }}</p>
<p>The HTML looks like so:</p>
<pre class="brush: html"><form>
<div class="nativeDatePicker">
<label for="month-visit">What Month would you like to visit us?</label>
<input type="month" id="month-visit" name="month-visit">
<span class="validity"></span>
</div>
<p class="fallbackLabel">What Month would you like to visit us?</p>
<div class="fallbackDatePicker">
<div>
<span>
<label for="month">Month:</label>
<select id="month" name="month">
<option selected>January</option>
<option>February</option>
<option>March</option>
<option>April</option>
<option>May</option>
<option>June</option>
<option>July</option>
<option>August</option>
<option>September</option>
<option>October</option>
<option>November</option>
<option>December</option>
</select>
</span>
<span>
<label for="year">Year:</label>
<select id="year" name="year">
</select>
</span>
</div>
</div>
</form></pre>
<p>The months are hardcoded (as they are always the same), while the year values are dynamically generated depending on the current year (see the code comments below for detailed explanations of how these functions work.)</p>
<div class="hidden">
<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>
</div>
<p>The other part of the code that may be of interest is the feature detection code — to detect whether the browser supports <code><input type="month"></code>, we create a new {{htmlelement("input")}} element, set its <code>type</code> to <code>month</code>, then immediately check what its type is set to — non-supporting browsers will return <code>text</code>, because the <code>date</code> type falls back to type <code>text</code>. If <code><input type="month"></code> is not supported, we hide the native picker and show the fallback picker UI ({{htmlelement("select")}}) instead.</p>
<pre class="brush: js">// define variables
var nativePicker = document.querySelector('.nativeDatePicker');
var fallbackPicker = document.querySelector('.fallbackDatePicker');
var fallbackLabel = document.querySelector('.fallbackLabel');
var yearSelect = document.querySelector('#year');
var monthSelect = document.querySelector('#month');
// hide fallback initially
fallbackPicker.style.display = 'none';
fallbackLabel.style.display = 'none';
// test whether a new date input falls back to a text input or not
var test = document.createElement('input');
test.type = 'month';
// if it does, run the code inside the if() {} block
if(test.type === 'text') {
// hide the native picker and show the fallback
nativePicker.style.display = 'none';
fallbackPicker.style.display = 'block';
fallbackLabel.style.display = 'block';
// populate the years dynamically
// (the months are always the same, therefore hardcoded)
populateYears();
}
function populateYears() {
// get the current year as a number
var date = new Date();
var year = date.getFullYear();
// Make this year, and the 100 years before it available in the year <select>
for(var i = 0; i <= 100; i++) {
var option = document.createElement('option');
option.textContent = year-i;
yearSelect.appendChild(option);
}
}</pre>
<h2 id="规范">规范</h2>
<table class="standard-table">
<thead>
<tr>
<th scope="col">规范</th>
<th scope="col">状态</th>
<th scope="col">备注</th>
</tr>
</thead>
<tbody>
<tr>
<td>{{SpecName('HTML WHATWG', 'forms.html#month-state-(type=month)', '<input type="month">')}}</td>
<td>{{Spec2('HTML WHATWG')}}</td>
<td> </td>
</tr>
</tbody>
</table>
<h2 id="浏览器兼容性">浏览器兼容性</h2>
<p>{{Compat("html.elements.input.input-month")}}</p>
<h2 id="参见">参见</h2>
<ul>
<li>The generic {{HTMLElement("input")}} element and the interface used to manipulate it, {{domxref("HTMLInputElement")}}</li>
<li><a href="/en-US/docs/Web/HTML/Date_and_time_formats">Date and time formats used in HTML</a></li>
<li><a href="/en-US/docs/Web/Guide/HTML/Forms/The_native_form_widgets#Date_and_time_picker">Date and Time picker tutorial</a></li>
<li><code><a href="/en-US/docs/Web/HTML/Element/input/datetime-local"><input type="datetime-local"></a></code>, <code><a href="/en-US/docs/Web/HTML/Element/input/date"><input type="date"></a></code>, <code><a href="/en-US/docs/Web/HTML/Element/input/time"><input type="time"></a></code>, and <code><a href="/en-US/docs/Web/HTML/Element/input/week"><input type="week"></a></code></li>
</ul>
|