我尝试计算两个HTML时间输入元素之间的差异。在某个时间改变的时刻,必须重新计算一次,不幸的是我不能彼此做到这一点。谁可以帮助我?
<input type="time" id="start" value="10:00" >
<input type="time" id="end" value="12:30" >
<input id="diff">
<script>
var start = document.getElementById("start").value;
var end = document.getElementById("end").value;
document.getElementById("start").onchange = function() {diff(start,end)};
document.getElementById("end").onchange = function() {diff(start,end)};
function diff(start, end) {
start = start.split(":");
end = end.split(":");
var startDate = new Date(0, 0, 0, start[0], start[1], 0);
var endDate = new Date(0, 0, 0, end[0], end[1], 0);
var diff = endDate.getTime() - startDate.getTime();
var hours = Math.floor(diff / 1000 / 60 / 60);
diff -= hours * 1000 * 60 * 60;
var minutes = Math.floor(diff / 1000 / 60);
return (hours < 9 ? "0" : "") + hours + ":" + (minutes < 9 ? "0" : "") + minutes;
}
document.getElementById("diff").value = diff(start, end);
</script>
答案 0 :(得分:1)
使用代码,您一次只能获得start和end的值。每次计算差值时都必须获取该值
尝试做
document.getElementById("start").onchange = function() {
var start = document.getElementById("start").value;
var end = document.getElementById("end").value;
diff(start,end)};
和其他元素相同。
答案 1 :(得分:1)
这个时差代码很棒!因此,如果您只需要对其进行更新,那么我会为您复制并稍微重新构建您的代码。同样,您的代码很棒:)
<input type="time" id="start" value="10:00" >
<input type="time" id="end" value="12:30" >
<input id="diff">
<script>
var start = document.getElementById("start").value;
var end = document.getElementById("end").value;
document.getElementById("start").onchange = function() {diff(start,end)};
document.getElementById("end").onchange = function() {diff(start,end)};
function diff(start, end) {
start = document.getElementById("start").value; //to update time value in each input bar
end = document.getElementById("end").value; //to update time value in each input bar
start = start.split(":");
end = end.split(":");
var startDate = new Date(0, 0, 0, start[0], start[1], 0);
var endDate = new Date(0, 0, 0, end[0], end[1], 0);
var diff = endDate.getTime() - startDate.getTime();
var hours = Math.floor(diff / 1000 / 60 / 60);
diff -= hours * 1000 * 60 * 60;
var minutes = Math.floor(diff / 1000 / 60);
return (hours < 9 ? "0" : "") + hours + ":" + (minutes < 9 ? "0" : "") + minutes;
}
setInterval(function(){document.getElementById("diff").value = diff(start, end);}, 1000); //to update time every second (1000 is 1 sec interval and function encasing original code you had down here is because setInterval only reads functions) You can change how fast the time updates by lowering the time interval
</script>
这就是您想要的,如果不需要的话,请告诉我,我将很乐意为您提供出色的代码:)