我有 2 个输入(type="time")。我想要在第一个输入字段中输入的时间获取 + 30 分钟并将其写入第二个输入字段中。有可能吗?我的 JS 不太好:I
<html>
<form>
<label for="start">Start: <input type="time" id="start" name="start" step="600"> </label><br>
<label for="ende">Ende: <input type="time" id="ende" name="ende" step="600"> </label>
<input type="submit" value="senden">
</form>
</html>
我想我需要在JS中获取输入ID并添加30分钟? 像这样:
document.getElementById('start').value;
...但是如何添加 30 分钟?
最佳答案
时间输入存储xx:xx
形式的字符串值,想法是向开始输入添加一个change
事件监听器,获取其值,添加30 分钟,然后将其分配给最终输入。
这是一个可运行的代码片段,显示了一种可能的解决方案以及分步注释:
// get input elements
const start = document.getElementById('start');
const end = document.getElementById('ende');
// add a change event listener to the start input
start.addEventListener('change', () => {
// get hours and minutes as integer values
let hours = parseInt(start.value.split(':')[0]);
let minutes = parseInt(start.value.split(':')[1]);
// add 30 minutes
minutes += 30;
// if an hour is exceeded, add it to hours instead
// and account for a day passing by
if (minutes >= 60) {
hours = (hours + 1) % 24;
minutes -= 60;
}
// reformat values as strings with a fix length of 2
hours = (hours < 10 ? `0${hours}` : `${hours}`);
minutes = (minutes < 10 ? `0${minutes}` : `${minutes}`);
// assign new value to the end input
end.value = `${hours}:${minutes}`;
});
<form>
<label for="start">Start: <input type="time" id="start" name="start" step="600"> </label><br>
<label for="ende">Ende: <input type="time" id="ende" name="ende" step="600"> </label>
<input type="submit" value="senden">
</form>
关于javascript - 输入时间加上 30 分钟,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57179330/