下面是一个片段,它做了我认为你想做的事情。我按照要求使用了您的代码,尽管有更有效的方法来计算两次之间的差异。看到 这个问题 如果你感兴趣。
<html> <head> <title>Time Past Since</title> </head> <body> <center id="time">Test</center> <script> window.resizeTo(300,100); updateTime(); setInterval(updateTime, 60000); function updateTime() { sd = new Date(); // Get system date (sd) sh = sd.getHours(); // Get system hour (sh) sm = sd.getMinutes(); // Get system minutes (sm) wh = (08); // Specify work start hour (wh) wm =(30); // Specify work start minute (wh) ts = ((sh *60 + sm) - (wh *60 + wm)); // Specify time since (ts) in minutes hs = Math.floor(ts/60); // Convert the hours (hs) ms = Math.round((ts/60 % 1) * 60); // Convert the minutes (ms) fh = hs < 10 ? "0" : ""; // Format Hours (fh) fm = ms < 10 ? "0" : ""; // Format Minutes (fm) document.getElementById("time").innerHTML = fh + hs + " hours " + fm + ms + " minutes."; } </script> </body> </html>
我将时间计算包装在一个名为的函数中 updateTime 并使其每60秒运行一次。它无需刷新即可更新文本。
updateTime
我命名函数而不是使它成为匿名函数,因为我们需要在首次加载页面时调用它。
如果我回答你的问题,请不要忘记点击绿色的“接受答案”按钮!
这不是最干净的方式,但听起来你并不在乎。
<html> <head> <title>Time Past Since</title> <script> window.resizeTo(300,100); setInterval(function(){ var sd = new Date(), // Get system date (sd) sh = sd.getHours(), // Get system hour (sh) sm = sd.getMinutes(), // Get system minutes (sm) wh = (08), // Specify work start hour (wh) wm =(30), // Specify work start minute (wh) ts = ((sh *60 + sm) - (wh *60 + wm)), // Specify time since (ts) in minutes hs = Math.floor(ts/60), // Convert the hours (hs) ms = Math.round((ts/60 % 1) * 60), // Convert the minutes (ms) fh = hs < 10 ? "0" : "", // Format Hours (fh) fm = ms < 10 ? "0" : "", // Format Minutes (fm) str = fh + hs + " hours " + fm + ms + " minutes."; document.getElementById('display').innerHTML = str; }, 60000); </script> </head> <body> <div><center id="display"></center></div> </body> </html>