2 回答

TA貢獻1770條經驗 獲得超3個贊
時間輸入存儲了一個表單的字符串值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>

TA貢獻1866條經驗 獲得超5個贊
您可以像這里提到的那樣在“:”處拆分值:如何將輸入類型時間的值傳遞給日期對象? 然后,您通過訪問拆分數組的正確位置并添加 30 來獲得分鐘數。然后將值重新組合在一起并執行以下操作:
document.getElementById("ende").value = newTime;
而 newTime 是您添加 30 分鐘的字符串。
添加回答
舉報