<input type =“ time” step =“ 1” />在Chromium中的.value中不返回秒

时间:2018-07-24 02:10:14

标签: javascript html5

请考虑以下输入字段

document.getElementById("inp").addEventListener(
  "change",
  function(e) {
    document.getElementById("div").textContent = e.target.value;
  }
);
<input type="time" step="1" value="00:00:00" id="inp" />
<div id="div">00:00:00</div>

在Firefox中进行测试时,该值是更改输入后的期望值-格式为hh:mm:ss。但是当在Chromium(67.0.3396.99)中进行测试时,当输入更改为具有0秒的任何内容时,例如01:00:00,value属性仅返回hh:mm。

这是否符合规范的正确/预期行为? (编辑:是。)主要问题:是否有一种我不知道的标准方法,比.value更可取,以便在hh:mm:ss中获取其值,或者我有诉诸JavaScript字符串解析?

2 个答案:

答案 0 :(得分:1)

JavaScript字符串解析的价值非常简单且易于实现:

document.getElementById("inp").addEventListener(
  "change",
  function(e) {
    let time = e.target.value;
    if (time.length < 6) { // missing :ss on chrome
      time += ':00'; // add it ourselves
    }
    document.getElementById("div").textContent = time;
  }
);
<input type="time" step="1" value="00:00:00" id="inp" />
<div id="div">00:00:00</div>

答案 1 :(得分:1)

The outputs of Firefox and Chromium are actually both consistent with the specs.

The HTML Living Standard (Last Updated 24 July 2018) states:

The value attribute, if specified and not empty, must have a value that is a valid time string.

And "valid time string" is defined as follows:

A string is a valid time string representing an hour hour, a minute minute, and a second second if it consists of the following components in the given order:

  1. Two ASCII digits, representing hour, in the range 0 ≤ hour ≤ 23
  2. A U+003A COLON character (:)
  3. Two ASCII digits, representing minute, in the range 0 ≤ minute ≤ 59
  4. If second is nonzero, or optionally if second is zero:
    1. A U+003A COLON character (:)
    2. Two ASCII digits, representing the integer part of second, in the range 0 ≤ s ≤ 59
    3. If second is not an integer, or optionally if second is an integer:
      1. A U+002E FULL STOP character (.)
      2. One, two, or three ASCII digits, representing the fractional part of second

Credits to user @int32_t for linking me to the current standard.