<input type="time">

time 类型的 <input> 元素创建输入字段,旨在让用户轻松输入时间(小时和分钟,以及可选的秒)。

¥<input> elements of type time create input fields designed to let the user easily enter a time (hours and minutes, and optionally seconds).

该控件的用户界面因浏览器而异;详细信息请参见 浏览器兼容性。在不受支持的浏览器中,该控件会正常降级到 <input type="text">

¥The control's user interface varies from browser to browser; see Browser compatibility for further details. In unsupported browsers, the control degrades gracefully to <input type="text">.

Try it

外貌

¥Appearance

Chrome 和 Opera

¥Chrome and Opera

在 Chrome/Opera 中,time 控件很简单,带有用于根据操作系统区域设置以 12 或 24 小时格式输入小时和分钟的插槽,以及用于递增和递减当前所选组件的向上和向下箭头。在某些版本中,提供了 "X" 按钮来清除控件的值。

¥In Chrome/Opera the time control is simple, with slots to enter hours and minutes in 12 or 24-hour format depending on operating system locale, and up and down arrows to increment and decrement the currently selected component. In some versions, an "X" button is provided to clear the control's value.

12-hour Chrome time input

12-hour

24-hour Chrome time input

24-hour

火狐浏览器

¥Firefox

Firefox 的 time 控件与 Chrome 的非常相似,只是它没有向上和向下箭头。它还根据系统区域设置使用 12 小时或 24 小时格式来输入时间。提供了 "X" 按钮来清除控件的值。

¥Firefox's time control is very similar to Chrome's, except that it doesn't have the up and down arrows. It also uses a 12- or 24-hour format for inputting times, based on system locale. An "X" button is provided to clear the control's value.

12-hour Firefox time input

12-hour

24-hour Firefox time input

24-hour

边缘

¥Edge

Edge time 的控制更为复杂,打开了带有滑动滚动的小时和分钟选择器。它与 Chrome 一样,根据系统区域设置使用 12 或 24 小时格式输入时间:

¥The Edge time control is somewhat more elaborate, opening up an hour and minute picker with sliding reels. It, like Chrome, uses a 12- or 24-hour format for inputting times, based on system locale:

12-hour Edge time input

12-hour

24-hour Edge time input

24-hour

¥Value

包含输入到输入中的时间值的字符串。

¥A string containing the value of the time entered into the input.

设置值属性

¥Setting the value attribute

你可以在创建 <input> 元素时通过在 value 属性中包含有效时间来设置输入的默认值,如下所示:

¥You can set a default value for the input by including a valid time in the value attribute when creating the <input> element, like so:

html
<label for="appt-time">Choose an appointment time: </label>
<input id="appt-time" type="time" name="appt-time" value="13:30" />

使用 JavaScript 设置值

¥Setting the value using JavaScript

你还可以使用 HTMLInputElement value 属性在 JavaScript 中获取和设置时间值,例如:

¥You can also get and set the time value in JavaScript using the HTMLInputElement value property, for example:

js
const timeControl = document.querySelector('input[type="time"]');
timeControl.value = "15:30";

时间值格式

¥Time value format

time 输入的 value 始终采用 24 小时格式,其中包含前导零:hh:mm,无论输入格式如何,都可能根据用户的区域设置(或由用户代理)进行选择。如果时间包括秒(参见 使用步骤属性),则格式始终为 hh:mm:ss。你可以在 时间字符串 中了解有关此输入类型使用的时间值格式的更多信息。

¥The value of the time input is always in 24-hour format that includes leading zeros: hh:mm, regardless of the input format, which is likely to be selected based on the user's locale (or by the user agent). If the time includes seconds (see Using the step attribute), the format is always hh:mm:ss. You can learn more about the format of the time value used by this input type in Time strings.

在此示例中,你可以通过输入时间并查看其随后的变化来查看时间输入的值。

¥In this example, you can see the time input's value by entering a time and seeing how it changes afterward.

首先,看一下 HTML。这很简单,使用我们之前看到的标签和输入,但添加了 <p> 元素和 <span> 来显示 time 输入的值:

¥First, a look at the HTML. This is simple enough, with the label and input as we've seen before, but with the addition of a <p> element with a <span> to display the value of the time input:

html
<form>
  <label for="startTime">Start time: </label>
  <input type="time" id="startTime" />
  <p>
    Value of the <code>time</code> input:
    <code> "<span id="value">n/a</span>"</code>.
  </p>
</form>

JavaScript 代码将代码添加到时间输入以监视 input 事件,每次输入元素的内容发生更改时都会触发该事件。发生这种情况时,<span> 的内容将替换为输入元素的新值。

¥The JavaScript code adds code to the time input to watch for the input event, which is triggered every time the contents of an input element change. When this happens, the contents of the <span> are replaced with the new value of the input element.

js
const startTime = document.getElementById("startTime");
const valueSpan = document.getElementById("value");

startTime.addEventListener(
  "input",
  () => {
    valueSpan.innerText = startTime.value;
  },
  false,
);

当提交包含 time 输入的表单时,该值会在包含在表单数据中之前进行编码。表单的时间输入数据条目将始终采用表单 name=hh%3Ammname=hh%3Amm%3Ass(如果包含秒)(请参阅 使用步骤属性)。

¥When a form including a time input is submitted, the value is encoded before being included in the form's data. The form's data entry for a time input will always be in the form name=hh%3Amm, or name=hh%3Amm%3Ass if seconds are included (see Using the step attribute).

附加属性

¥Additional attributes

除了所有 <input> 元素共有的属性外,time 输入还提供以下属性。

¥In addition to the attributes common to all <input> elements, time inputs offer the following attributes.

注意:与许多数据类型不同,时间值具有周期域,这意味着这些值达到可能的最高值,然后再次回到起点。例如,指定 min14:00max2:00,意味着允许的时间值从下午 2:00 开始,一直持续到午夜到第二天,在凌晨 2:00 结束。请参阅本文的 午夜交叉最小和最大 部分了解更多信息。

¥Note: Unlike many data types, time values have a periodic domain, meaning that the values reach the highest possible value, then wrap back around to the beginning again. For example, specifying a min of 14:00 and a max of 2:00 means that the permitted time values start at 2:00 PM, run through midnight to the next day, ending at 2:00 AM. See more in the making min and max cross midnight section of this article.

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

表示最晚接受时间的字符串,在与上述相同的 时间值格式 中指定。如果指定的字符串不是有效时间,则不会设置最大值。

¥A string indicating the latest time to accept, specified in the same time value format as described above. If the specified string isn't a valid time, no maximum value is set.

min

指定最早接受时间的字符串,在前面描述的 时间值格式 中给出。如果指定的值不是有效的时间字符串,则不会设置最小值。

¥A string specifying the earliest time to accept, given in the time value format described previously. If the value specified isn't a valid time string, no minimum value is set.

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.

对于 time 输入,step 的值以秒为单位给出,缩放因子为 1000(因为基础数值以毫秒为单位)。step 的默认值为 60,表示 60 秒(或 1 分钟,或 60000 毫秒)。

¥For time inputs, the value of step is given in seconds, with a scaling factor of 1000 (since the underlying numeric value is in milliseconds). The default value of step is 60, indicating 60 seconds (or 1 minute, or 60,000 milliseconds).

目前,还不清楚当与 time 输入一起使用时 any 的值对于 step 意味着什么。一旦确定该信息,我们将立即更新。

¥At this time, it's unclear what a value of any means for step when used with time inputs. This will be updated as soon as that information is determined.

使用时间输入

¥Using time inputs

时间的基本用途

¥Basic uses of time

<input type="time"> 最简单的使用涉及基本的 <input><label> 元素组合,如下所示:

¥The simplest use of <input type="time"> involves a basic <input> and <label> element combination, as seen below:

html
<form>
  <label for="appt-time">Choose an appointment time: </label>
  <input id="appt-time" type="time" name="appt-time" />
</form>

控制输入大小

¥Controlling input size

<input type="time"> 不支持诸如 size 之类的表单大小调整属性,因为时间的字符数长度始终大致相同。你必须求助于 CSS 来满足尺码需求。

¥<input type="time"> doesn't support form sizing attributes such as size, since times are always about the same number of characters long. You'll have to resort to CSS for sizing needs.

使用步骤属性

¥Using the step attribute

你可以使用 step 属性来改变每当时间增加或减少时跳跃的时间量(例如,单击小箭头小部件时时间一次移动 10 分钟)。

¥You can use the step attribute to vary the amount of time jumped whenever the time is incremented or decremented (for example, so the time moves by 10 minutes at a time when clicking the little arrow widgets).

注意:该属性在浏览器中会产生一些奇怪的影响,因此并不完全可靠。

¥Note: This property has some strange effects across browsers, so is not completely reliable.

它采用一个整数值,该值等于你要增加的秒数;默认值为 60 秒或一分钟。如果指定小于 60 秒(1 分钟)的值,time 输入将在小时和分钟旁边显示秒输入区域:

¥It takes an integer value that equates to the number of seconds you want to increment by; the default value is 60 seconds, or one minute. If you specify a value of less than 60 seconds (1 minute), the time input will show a seconds input area alongside the hours and minutes:

html
<form>
  <label for="appt-time">Choose an appointment time: </label>
  <input id="appt-time" type="time" name="appt-time" step="2" />
</form>

在 Chrome 和 Opera(这是唯一显示向上/向下迭代箭头的浏览器)中,单击箭头会将秒值更改两秒,但不会影响小时或分钟。仅当你指定以秒为单位的分钟(或小时)数(例如 120 表示 2 分钟,或 7200 表示 2 小时)时,分钟(或小时)才可用于步进。

¥In Chrome and Opera, which are the only browsers to show up/down iteration arrows, clicking the arrows changes the seconds value by two seconds, but doesn't affect the hours or minutes. Minutes (or hours) can only be used for stepping when you specify a number of minutes (or hours) in seconds, such as 120 for 2 minutes, or 7200 for 2 hours).

在 Firefox 中,没有箭头,因此不使用 step 值。但是,如果它确实在分钟部分旁边添加了秒输入区域。

¥In Firefox, there are no arrows, so the step value isn't used. However, providing it does add the seconds input area adjacent to the minutes section.

步骤值似乎在 Edge 中没有效果。

¥The steps value seems to have no effect in Edge.

注意:使用 step 似乎会导致验证无法正常工作(如下一节所示)。

¥Note: Using step seems to cause validation to not work properly (as seen in the next section).

验证

¥Validation

默认情况下,<input type="time"> 不对输入的值应用任何验证,除了用户代理界面通常不允许你输入时间值以外的任何内容。这很有帮助(假设用户代理完全支持 time 输入),但你不能完全依赖该值作为正确的时间字符串,因为它可能是允许的空字符串 ("")。该值也可能看起来大致像有效时间,但并不正确,例如 25:05

¥By default, <input type="time"> does not apply any validation to entered values, other than the user agent's interface generally not allowing you to enter anything other than a time value. This is helpful (assuming the time input is fully supported by the user agent), but you can't entirely rely on the value to be a proper time string, since it might be an empty string (""), which is allowed. It's also possible for the value to look roughly like a valid time but not be correct, such as 25:05.

设置最大和最小时间

¥Setting maximum and minimum times

你可以使用 minmax 属性来限制用户可以选择的有效时间。在以下示例中,我们设置最小时间为 12:00,最大时间为 18:00

¥You can use the min and max attributes to restrict the valid times that can be chosen by the user. In the following example we are setting a minimum time of 12:00 and a maximum time of 18:00:

html
<form>
  <label for="appt-time">
    Choose an appointment time (opening hours 12:00 to 18:00):
  </label>
  <input id="appt-time" type="time" name="appt-time" min="12:00" max="18:00" />
  <span class="validity"></span>
</form>

这是上面示例中使用的 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.

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;
}

这里的结果是:

¥The result here is that:

  • 仅 12:00 至 18:00 之间的时间被视为有效;超出该范围的时间将被视为无效。
  • 根据你使用的浏览器,你可能会发现指定范围之外的时间甚至可能无法在时间选择器(例如 Edge)中选择。

午夜交叉最小和最大

¥Making min and max cross midnight

通过将 min 属性设置为大于 max 属性,有效时间范围将环绕午夜,以生成跨越午夜的有效时间范围。任何其他输入类型均不支持此功能。虽然此功能已是 在 HTML 规范中,但尚未得到普遍支持。基于 Chrome 的浏览器从版本 82 开始支持它,Firefox 在版本 76 中添加了它。自版本 14.1 起,Safari 不支持此功能。为出现这种情况做好准备:

¥By setting a min attribute greater than the max attribute, the valid time range will wrap around midnight to produce a valid time range which crosses midnight. This functionality is not supported by any other input types. While this feature is in the HTML spec, it is not yet universally supported. Chrome-based browsers support it starting in version 82 and Firefox added it in version 76. Safari as of version 14.1 does not support this. Be prepared for this situation to arise:

js
const input = document.createElement("input");
input.type = "time";
input.min = "23:00";
input.max = "01:00";
input.value = "23:59";

if (input.validity.valid && input.type === "time") {
  // <input type=time> reversed range supported
} else {
  // <input type=time> reversed range unsupported
}

所需时间

¥Making times required

此外,你可以使用 required 属性强制填写时间。因此,如果你尝试提交超出设置范围的时间或空时间字段,支持的浏览器将显示错误。

¥In addition, you can use the required attribute to make filling in the time mandatory. As a result, supporting browsers will display an error if you try to submit a time that is outside the set bounds, or an empty time field.

让我们看一个例子;在这里,我们设置了最小和最大时间,并且还设置了必填字段:

¥Let's look at an example; here we've set minimum and maximum times, and also made the field required:

html
<form>
  <div>
    <label for="appt-time">
      Choose an appointment time (opening hours 12:00 to 18:00):
    </label>
    <input
      id="appt-time"
      type="time"
      name="appt-time"
      min="12:00"
      max="18:00"
      required />
    <span class="validity"></span>
  </div>
  <div>
    <input type="submit" value="Submit form" />
  </div>
</form>

如果你尝试提交时间不完整(或时间超出设定范围)的表单,浏览器会显示错误。现在尝试使用示例:

¥If you try to submit the form with an incomplete time (or with a time outside the set bounds), the browser displays an error. Try playing with the example now:

警告: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

如前所述,旧版本的 Safari 和其他一些不太常见的浏览器本身不支持时间输入。一般来说,否则,支持很好 - 特别是在移动平台上,这些平台往往有非常好的用户界面来指定时间值。例如,Android Chrome 上的 time 选择器如下所示:

¥As mentioned, older versions of Safari and a few other, less common, browsers don't support time inputs natively. In general, otherwise, support is good — especially on mobile platforms, which tend to have very nice user interfaces for specifying a time value. For example, the time picker on Chrome for Android looks like this:

Phone screen showing modal dialog with 10:21 as a header. The 10 is fully opaque. The 21 is not. The main area has a circle with the numbers 1 - 12 in a ring, and the number 13 -24 on an inner ring. The number 10 is highlighted with a blue circle. The buttons at the bottom are clear, cancel, and set.

不支持时间输入的浏览器会优雅地降级为文本输入,但这会在用户界面的一致性(所呈现的控件将不同)和数据处理方面产生问题。

¥Browsers that don't support time inputs 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.

第二个问题更为严重;如前所述,time 输入值始终标准化为 hh:mmhh:mm:ss 格式。另一方面,对于文本输入,默认情况下浏览器不知道时间应该采用什么格式,并且人们书写时间的方式有多种,例如:

¥The second problem is the more serious; as mentioned previously, time inputs' values are always normalized to the format hh:mm or hh:mm:ss. With a text input, on the other hand, by default the browser has no idea of what format the time should be in, and there are multiple ways in which people write times, such as:

  • 3.00 pm
  • 3:00pm
  • 15:00
  • 3 o'clock in the afternoon
  • ETC。

解决此问题的一种方法是在 time 输入上放置 pattern 属性。即使 time 输入不使用它,text 输入回退也会使用它。例如,尝试在不支持时间输入的浏览器中查看以下演示:

¥One way around this is to put a pattern attribute on your time input. Even though the time input doesn't use it, the text input fallback will. For example, try viewing the following demo in a browser that doesn't support time inputs:

html
<form>
  <div>
    <label for="appt-time">
      Choose an appointment time (opening hours 12:00 to 18:00):
    </label>
    <input
      id="appt-time"
      type="time"
      name="appt-time"
      min="12:00"
      max="18:00"
      required
      pattern="[0-9]{2}:[0-9]{2}" />
    <span class="validity"></span>
  </div>
  <div>
    <input type="submit" value="Submit form" />
  </div>
</form>

如果你尝试提交它,如果你的条目与模式 nn:nn 不匹配(其中 n 是 0 到 9 之间的数字),你会看到不支持的浏览器现在会显示一条错误消息(并将输入高亮为无效)。当然,这并不能阻止人们输入无效时间或遵循模式的格式不正确的时间。

¥If you try submitting it, you'll see that non-supporting browsers now display an error message (and highlight the input as invalid) if your entry doesn't match the pattern nn:nn, where n is a number from 0 to 9. Of course, this doesn't stop people from entering invalid times, or incorrectly formatted times that follow the pattern.

然后存在的问题是用户不知道时间预计采用什么格式。

¥Then there's the problem of the user having no idea exactly what format the time is expected to be in.

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;
}

目前,以跨浏览器方式处理表单中的时间的最佳方法是让用户在单独的控件中输入小时和分钟(如果需要,还可以输入秒)(<select> 元素很流行;请参阅下面的示例),或使用 JavaScript 库,例如 jQuery 时间选择器插件

¥The best way to deal with times in forms in a cross-browser way, for the time being, is to get the user to enter the hours and minutes (and seconds if required) in separate controls (<select> elements are popular; see below for an example), or use JavaScript libraries such as the jQuery timepicker plugin.

示例

¥Examples

在此示例中,我们创建两组界面元素用于选择时间:使用 <input type="time"> 创建的原生选择器,以及一组两个 <select> 元素,用于在不支持原生输入的旧浏览器中选择小时/分钟。

¥In this example, we create two sets of interface elements for choosing times: a native picker created with <input type="time">, and a set of two <select> elements for choosing hours/minutes in older browsers that don't support the native input.

HTML 看起来像这样:

¥The HTML looks like so:

html
<form>
  <div class="nativeTimePicker">
    <label for="appt-time">
      Choose an appointment time (opening hours 12:00 to 18:00):
    </label>
    <input
      id="appt-time"
      type="time"
      name="appt-time"
      min="12:00"
      max="18:00"
      required />
    <span class="validity"></span>
  </div>
  <p class="fallbackLabel">
    Choose an appointment time (opening hours 12:00 to 18:00):
  </p>
  <div class="fallbackTimePicker">
    <div>
      <span>
        <label for="hour">Hour:</label>
        <select id="hour" name="hour"></select>
      </span>
      <span>
        <label for="minute">Minute:</label>
        <select id="minute" name="minute"></select>
      </span>
    </div>
  </div>
</form>

<select> 元素的小时和分钟值是动态生成的。

¥The hour and minutes values for their <select> elements are dynamically generated.

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;
}

代码中可能感兴趣的另一部分是功能检测代码 - 为了检测浏览器是否支持 <input type="time">,我们创建一个新的 <input> 元素,尝试将其 type 设置为 time,然后立即检查其类型设置为什么 - 非 - 支持的浏览器将返回 text,因为 time 类型会回退到 text 类型。如果不支持 <input type="time">,我们将隐藏原生选择器并显示后备选择器 UI (<select>)。

¥The other part of the code that may be of interest is the feature detection code — to detect whether the browser supports <input type="time">, we create a new <input> element, try setting its type to time, then immediately check what its type is set to — non-supporting browsers will return text, because the time type falls back to type text. If <input type="time"> is not supported, we hide the native picker and show the fallback picker UI (<select>s) instead.

js
// Define variables
const nativePicker = document.querySelector(".nativeTimePicker");
const fallbackPicker = document.querySelector(".fallbackTimePicker");
const fallbackLabel = document.querySelector(".fallbackLabel");

const hourSelect = document.querySelector("#hour");
const minuteSelect = document.querySelector("#minute");

// Hide fallback initially
fallbackPicker.style.display = "none";
fallbackLabel.style.display = "none";

// Test whether a new time input falls back to a text input or not
const test = document.createElement("input");

try {
  test.type = "time";
} 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 hours and minutes dynamically
  populateHours();
  populateMinutes();
}

function populateHours() {
  // Populate the hours <select> with the 6 open hours of the day
  for (let i = 12; i <= 18; i++) {
    const option = document.createElement("option");
    option.textContent = i;
    hourSelect.appendChild(option);
  }
}

function populateMinutes() {
  // populate the minutes <select> with the 60 hours of each minute
  for (let i = 0; i <= 59; i++) {
    const option = document.createElement("option");
    option.textContent = i < 10 ? `0${i}` : i;
    minuteSelect.appendChild(option);
  }
}

// make it so that if the hour is 18, the minutes value is set to 00
// — you can't select times past 18:00
function setMinutesToZero() {
  if (hourSelect.value === "18") {
    minuteSelect.value = "00";
  }
}

hourSelect.onchange = setMinutesToZero;
minuteSelect.onchange = setMinutesToZero;

技术摘要

¥Technical Summary

代表时间的字符串或空。
活动 changeinput
支持的通用属性 autocompletelistreadonlystep
IDL 属性 valuevalueAsDatevalueAsNumberlist
DOM 接口

HTMLInputElement

方法 select()stepDown()stepUp()
隐式 ARIA 角色 no corresponding role

规范

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

¥Specifications

浏览器兼容性

BCD tables only load in the browser

¥Browser compatibility

也可以看看