<input type="month">
month
类型的 <input>
元素创建输入字段,允许用户输入月份和年份,从而可以轻松输入月份和年份。该值是一个字符串,其值的格式为“YYYY-MM
”,其中 YYYY
是四位数年份,MM
是月份数字。
¥<input>
elements of type month
create input fields that let the user enter a month and year allowing a month and year to be easily entered.
The value is a string whose value is in the format "YYYY-MM
", where YYYY
is the four-digit year and MM
is the month number.
Try it
一般来说,该控件的 UI 会因浏览器的不同而有所不同;目前支持并不完善,只有桌面上的 Chrome/Opera 和 Edge(以及大多数现代移动浏览器版本)具有可用的实现。在不支持 month
输入的浏览器中,控件会优雅地降级为简单的 <input type="text">
,尽管可能会自动验证输入的文本以确保其格式符合预期。
¥The control's UI varies in general from browser to browser; at the moment support is patchy, with only Chrome/Opera and Edge on desktop — and most modern mobile browser versions — having usable implementations.
In browsers that don't support month
inputs, the control degrades gracefully to a simple <input type="text">
, although there may be automatic validation of the entered text to ensure it's formatted as expected.
对于那些使用不支持 month
的浏览器的人来说,下面的屏幕截图显示了它在 Chrome 和 Opera 中的样子。单击右侧的向下箭头会弹出一个日期选择器,你可以在其中选择月份和年份。
¥For those of you using a browser that doesn't support month
, the screenshot below shows what it looks like in Chrome and Opera.
Clicking the down arrow on the right-hand side brings up a date picker that lets you select the month and year.
Microsoft Edge month
控件如下所示:
¥The Microsoft Edge month
control looks like this:
值
¥Value
表示输入到输入中的月份和年份值的字符串,格式为 YYYY-MM(四位或更多位年份,然后是连字符 (“-
”),后跟两位数月份)。该输入类型使用的月份字符串的格式在 月份字符串 中描述。
¥A string representing the value of the month and year entered into the input, in the form YYYY-MM (four or more digit year, then a hyphen ("-
"), followed by the two-digit month).
The format of the month string used by this input type is described in Month strings.
设置默认值
¥Setting a default value
你可以通过在 value
属性中包含月份和年份来设置输入控件的默认值,如下所示:
¥You can set a default value for the input control by including a month and year inside the value
attribute, like so:
<label for="bday-month">What month were you born in?</label>
<input id="bday-month" type="month" name="bday-month" value="2001-06" />
需要注意的一点是,显示的日期格式与实际的 value
不同;大多数 user agents 根据用户操作系统设置的区域设置,以适合区域设置的形式显示月份和年份,而日期 value
始终采用 yyyy-MM
格式。
¥One thing to note is that the displayed date format differs from the actual value
; most user agents display the month and year in a locale-appropriate form, based on the set locale of the user's operating system, whereas the date value
is always formatted yyyy-MM
.
例如,当上面的值提交到服务器时,它将看起来像 bday-month=1978-06
。
¥When the above value is submitted to the server, for example, it will look like bday-month=1978-06
.
使用 JavaScript 设置值
¥Setting the value using JavaScript
你还可以使用 HTMLInputElement.value
属性在 JavaScript 中获取和设置日期值,例如:
¥You can also get and set the date value in JavaScript using the HTMLInputElement.value
property, for example:
<label for="bday-month">What month were you born in?</label>
<input id="bday-month" type="month" name="bday-month" />
const monthControl = document.querySelector('input[type="month"]');
monthControl.value = "2001-06";
附加属性
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
属性的值不是“yyyy-MM
”格式的有效字符串,则该元素没有最大值。
¥The latest year and month, in the string format discussed in the Value section above, to accept.
If the value
entered into the element exceeds this, the element fails constraint validation.
If the value of the max
attribute isn't a valid string in "yyyy-MM
" format, then the element has no maximum value.
该值指定的年月对必须晚于或等于 min
属性指定的年月对。
¥This value must specify a year-month pairing later than or equal to the one specified by the min
attribute.
min
接受的最早年份和月份,采用与上述相同的“yyyy-MM
”格式。如果元素的 value
小于此值,则该元素未通过 约束验证。如果为 min
指定的值不是有效的年份和月份字符串,则输入没有最小值。
¥The earliest year and month to accept, in the same "yyyy-MM
" format described above.
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 year and month string, the input has no minimum value.
该值必须是早于或等于 max
属性指定的年月对。
¥This value must be a year-month pairing which is earlier than or equal to the one specified by the max
attribute.
readonly
布尔属性,如果存在,则意味着用户无法编辑该字段。然而,它的 value
仍然可以通过直接设置 HTMLInputElement.value
属性值的 JavaScript 代码进行更改。
¥A Boolean attribute which, if present, means this field cannot be edited by the user.
Its value
can, however, still be changed from JavaScript code that directly sets the value of 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 thereadonly
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
意味着不暗示任何步进,并且允许任何值(除非其他约束,例如 min
和 max
)。
¥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.
对于 month
输入,step
的值以月为单位给出,缩放因子为 1(因为基础数值也是以月为单位)。step
的默认值为 1 个月。
¥For month
inputs, the value of step
is given in months, with a scaling factor of 1 (since the underlying numeric value is also in months).
The default value of step
is 1 month.
使用月份输入
¥Using month inputs
与日期相关的输入(包括 month
)乍一看听起来很方便;他们承诺提供一个简单的用户界面来选择日期,并且无论用户的区域设置如何,他们都会标准化发送到服务器的数据格式。然而,<input type="month">
存在问题,因为目前许多主流浏览器尚不支持它。
¥Date-related inputs (including month
) sound convenient at first glance; they promise an easy UI for choosing dates, and they normalize the data format sent to the server, regardless of the user's locale.
However, there are issues with <input type="month">
because at this time, many major browsers don't yet support it.
我们将了解 <input type="month">
的基本和更复杂的用法,然后在 处理浏览器支持) 部分中提供有关缓解浏览器支持问题的建议。
¥We'll look at basic and more complex uses of <input type="month">
, then offer advice on mitigating the browser support issue in the section Handling browser support).
月份的基本用法
¥Basic uses of month
<input type="month">
最简单的使用涉及基本的 <input>
和 <label>
元素组合,如下所示:
¥The simplest use of <input type="month">
involves a basic <input>
and <label>
element combination, as seen below:
<form>
<label for="bday-month">What month were you born in?</label>
<input id="bday-month" type="month" name="bday-month" />
</form>
设置最大和最小日期
¥Setting maximum and minimum dates
你可以使用 min
和 max
属性来限制用户可以选择的日期范围。在以下示例中,我们指定最小月份为 1900-01
,最大月份为 2013-12
:
¥You can use the min
and max
attributes to restrict the range of dates that the user can choose.
In the following example we specify a minimum month of 1900-01
and a maximum month of 2013-12
:
<form>
<label for="bday-month">What month were you born in?</label>
<input
id="bday-month"
type="month"
name="bday-month"
min="1900-01"
max="2013-12" />
</form>
这里的结果是:
¥The result here is that:
- 只能选择 1900 年 1 月至 2013 年 12 月之间的月份;无法在控件中滚动到该范围之外的月份。
- 根据你使用的浏览器,你可能会发现指定范围之外的月份可能无法在月份选择器中选择(例如 Edge),或者无效(参见 验证)但仍然可用(例如 Chrome)。
控制输入大小
验证
¥Validation
默认情况下,<input type="month">
不对输入的值应用任何验证。UI 实现通常不允许你输入任何非日期的内容(这很有帮助),但你仍然可以在 month
输入为空的情况下提交表单,或输入无效日期(例如 4 月 32 日)。
¥By default, <input type="month">
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 submit the form with the month
input empty, or enter an invalid date (e.g. the 32nd of April).
为了帮助避免这种情况,你可以使用 min
和 max
来限制可用日期(请参阅 设置最大和最小日期),此外还使用 required
属性强制填写日期。因此,如果你尝试提交超出设置范围的日期或空日期字段,支持的浏览器将显示错误。
¥To help avoid this, you can use min
and max
to restrict the available dates (see Setting maximum and minimum dates), and in addition use the required
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.
让我们看一个例子;在这里,我们设置了最小和最大日期,并且还设置了必填字段:
¥Let's look at an example; here we've set minimum and maximum dates, and also made the field required:
<form>
<div>
<label for="month">
What month would you like to visit (June to Sept.)?
</label>
<input
id="month"
type="month"
name="month"
min="2022-06"
max="2022-09"
required />
<span class="validity"></span>
</div>
<div>
<input type="submit" value="Submit form" />
</div>
</form>
如果你尝试在未指定月份和年份的情况下提交表单(或日期超出设定范围),浏览器将显示错误。现在尝试使用示例:
¥If you try to submit the form without both the month and year specified (or with a date outside the set bounds), the browser displays an error. Try playing with the example now:
对于那些不使用支持浏览器的人来说,这是一个屏幕截图:
¥Here's a screenshot for those of you who aren't using a supporting browser:
这是上面示例中使用的 CSS。这里我们利用 :valid
和 :invalid
CSS 属性根据当前值是否有效来设置输入样式。我们必须将图标放在输入旁边的 <span>
上,而不是放在输入本身上,因为在 Chrome 中,生成的内容放置在表单控件内,无法有效设置样式或显示。
¥Here's the CSS used in the above example.
Here we make use of the :valid
and :invalid
CSS properties to style the input based on whether the current value is valid.
We had to put the icons on a <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.
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;
}
警告:HTML 表单验证不能替代确保输入数据格式正确的脚本。对于某人来说,对 HTML 进行调整以绕过验证或完全删除它太容易了。其他人也有可能完全绕过你的 HTML 并将数据直接提交到你的服务器。如果你的服务器端代码无法验证其接收到的数据,则当提交格式不正确的数据(或数据太大、类型错误等)时,可能会发生灾难。
¥Warning: HTML form validation is not 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 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).
处理浏览器支持
¥Handling browser support
如上所述,在撰写本文时使用日期输入的主要问题是许多主要浏览器尚未全部实现;只有 Chrome/Opera 和 Edge 在桌面上支持它,而大多数现代浏览器在移动设备上支持它。例如,Android Chrome 上的 month
选择器如下所示:
¥As mentioned above, the major problem with using date inputs at the time of writing is that many major browsers don't yet implement them all; only Chrome/Opera and Edge support it on desktop, and most modern browsers on mobile.
As an example, the month
picker on Chrome for Android looks like this:
不支持的浏览器会优雅地降级为文本输入,但这会在用户界面的一致性(所提供的控件将有所不同)和数据处理方面产生问题。
¥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.
第二个问题是两个问题中更严重的一个。如前所述,使用 month
输入时,实际值始终标准化为 yyyy-mm
格式。另一方面,在其默认配置中,text
输入不知道日期应该采用什么格式,这是一个问题,因为人们编写日期的不同方式有很多。例如:
¥The second problem is the more serious of the two.
As mentioned earlier, with a month
input the actual value is always normalized to the format yyyy-mm
.
On the other hand, in its default configuration, a text
input has no idea what format the date should be in, and this is an issue because of the number of different ways in which people write dates.
For example:
mmyyyy
(072022)mm/yyyy
(07/2022)mm-yyyy
(07-2022)yyyy-mm
(2022-07)Month yyyy
(2022 年 7 月)- 等等……
解决此问题的一种方法是在 month
输入上放置 pattern
属性。即使 month
输入不使用它,如果浏览器将其视为 text
输入,也会使用该模式。例如,尝试在不支持 month
输入的浏览器中查看以下演示:
¥One way around this is to put a pattern
attribute on your month
input.
Even though the month
input doesn't use it, if the browser falls back to treating it like a text
input, the pattern will be used.
For example, try viewing the following demo in a browser that doesn't support month
inputs:
<form>
<div>
<label for="month">
What month would you like to visit (June to Sept.)?
</label>
<input
id="month"
type="month"
name="month"
min="2022-06"
max="2022-09"
required
pattern="[0-9]{4}-[0-9]{2}" />
<span class="validity"></span>
</div>
<div>
<input type="submit" value="Submit form" />
</div>
</form>
如果你尝试提交它,如果你的输入与模式 nnnn-nn
不匹配(其中 n
是 0 到 9 之间的数字),你会看到浏览器现在显示一条错误消息(并高亮输入无效)。当然,这并不能阻止人们输入无效日期(例如 0000-42
)或遵循该模式的格式不正确的日期。
¥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 nnnn-nn
, where n
is a number from 0 to 9.
Of course, this doesn't stop people from entering invalid dates (such as 0000-42
), or incorrectly formatted dates that follow the pattern.
还有一个问题是用户不一定知道需要使用多种日期格式中的哪一种。我们还有工作要做。
¥There's also the problem that the user won't necessarily know which of the many date formats is expected. We have work left to do.
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;
}
以跨浏览器方式处理表单中的日期的最佳方法(直到所有主要浏览器都支持它们一段时间)是让用户在单独的控件中输入月份和年份(<select>
元素很流行;请参阅下面的实现),或使用 JavaScript 库,例如 jQuery 日期选择器 插件。
¥The best way to deal with dates in forms in a cross-browser way (until all major browsers have supported them for a while) is to get the user to enter the month and year in separate controls (<select>
elements being popular; see below for an implementation), or use JavaScript libraries such as the jQuery date picker plugin.
示例
¥Examples
在此示例中,我们创建两组 UI 元素,每组都旨在让用户选择月份和年份。第一个是原生 month
输入,另一个是一对 <select>
元素,允许独立选择月份和年份,以便与尚不支持 <input type="month">
的浏览器兼容。
¥In this example, we create two sets of UI elements, each designed to let the user select a month and year.
The first is a native month
input, and the other is a pair of <select>
elements that allow choosing a month and year independently, for compatibility with browsers that don't yet support <input type="month">
.
HTML
请求月份和年份的表单如下所示:
¥The form that requests the month and year looks like this:
<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>
具有 ID nativeDatePicker
的 <div>
使用 month
输入类型来请求月份和年份,而具有 ID fallbackDatePicker
的 <div>
使用一对 <select>
元素。第一个请求月份,第二个请求年份。
¥The <div>
with the ID nativeDatePicker
uses the month
input type to request the month and year, while the <div>
with the ID fallbackDatePicker
instead uses a pair of <select>
elements.
The first requests the month, and the second the year.
用于选择月份的 <select>
是用月份名称硬编码的,因为它们不会改变(不考虑本地化)。可用年份值的列表是根据当前年份动态生成的(有关这些函数如何工作的详细说明,请参阅下面的代码注释)。
¥The <select>
for choosing the month is hardcoded with the names of the months, as they don't change (leaving localization out of things).
The list of available year values is dynamically generated depending on the current year (see the code comments below for detailed explanations of how these functions work).
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
下面是 JavaScript 代码,用于选择使用哪种方法并设置要包含在非本地年份 <select>
中的年份列表。
¥The JavaScript code that handles selecting which approach to use and to set up the list of years to include in the non-native year <select>
follows.
该示例中最令人感兴趣的部分可能是特性检测代码。为了检测浏览器是否支持 <input type="month">
,我们创建一个新的 <input>
元素,尝试将其 type
设置为 month
,然后立即检查其类型设置为什么。不支持类型 month
的浏览器将返回 text
,因为这是不支持时回退到的月份。如果不支持 <input type="month">
,我们将隐藏原生选择器并显示后备选择器 UI。
¥The part of the example that may be of most interest is the feature detection code.
In order to detect whether the browser supports <input type="month">
, we create a new <input>
element, try setting its type
to month
, then immediately check what its type is set to.
Browsers that don't support type month
will return text
, since that's What month falls back to when not supported.
If <input type="month">
is not supported, we hide the native picker and show the fallback picker UI instead.
// Get UI elements
const nativePicker = document.querySelector(".nativeDatePicker");
const fallbackPicker = document.querySelector(".fallbackDatePicker");
const fallbackLabel = document.querySelector(".fallbackLabel");
const yearSelect = document.querySelector("#year");
const 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
const test = document.createElement("input");
try {
test.type = "month";
} catch (e) {
console.log(e.description);
}
// 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
const date = new Date();
const year = date.getFullYear();
// Make this year, and the 100 years before it available in the year <select>
for (let i = 0; i <= 100; i++) {
const option = document.createElement("option");
option.textContent = year - i;
yearSelect.appendChild(option);
}
}
注意:请记住,有些年份有 53 周(参见 每年几周)!开发生产应用时需要考虑到这一点。
¥Note: Remember that some years have 53 weeks in them (see Weeks per year)! You'll need to take this into consideration when developing production apps.
技术总结
¥Technical summary
值 | 代表月份和年份的字符串,或者为空。 |
活动 | change 和 input |
支持的通用属性 |
autocomplete ,
list ,
readonly ,
step
|
IDL 属性 |
list ,
value ,
valueAsDate ,
valueAsNumber
|
DOM 接口 | |
方法 | select() , stepDown() , stepUp() . |
隐式 ARIA 角色 | no corresponding role |
规范
Specification |
---|
HTML Standard # month-state-(type=month) |
浏览器兼容性
BCD tables only load in the browser