解决基于 javascript 的倒计时中的负值
我正在创建一个倒计时来计算我打算观看的 2012 年欧洲杯比赛之间的时间。 我已经提供了它的工作版本,但我不明白为什么它有时会给我负值。 我认为这与我使用 getTime() 方法编写它的方式有关。 这是我的代码,你们能帮我找出解决这些负值的方法吗? 预先非常感谢您。
<body onload="timeto2012()">
<script type="text/javascript">
function timeto2012() {
var euro2012 = new Date(2012, 5, 10, 20, 45);
var euro2012ms = euro2012.getTime();
var now = new Date();
var nowms = now.getTime();
var diff = euro2012ms - nowms;
var seconds = 1000;
var minutes = seconds*60;
var hours = minutes*60;
var days = hours*24;
var years = days*365;
var ddays = diff/days;
var dhours = (ddays - Math.round(ddays,1))*24;
var dminutes = (dhours - Math.round(dhours))*60;
var dseconds = (dminutes - Math.round(dminutes))*60;
document.getElementById("time").innerHTML='' + Math.round(ddays,1) +' days '+ Math.round(dhours,1) +' hours '+ Math.round(dminutes,1) +' minutes '+ Math.round(dseconds,1) + ' seconds remaining';
}
t=setInterval(timeto2012,500);
</script>
<div id="time"></div>
</body>
I am creating a countdown to count the time between a match of the euro2012 that I intend to watch.
I've come with a working version of it but I don't understand why it gives me sometimes negative values.
I think it has to do with the way I wrote it, using the getTime() method.
Here is my code, could you guys help me find out to solve those negative values?
Thank you very much in advance.
<body onload="timeto2012()">
<script type="text/javascript">
function timeto2012() {
var euro2012 = new Date(2012, 5, 10, 20, 45);
var euro2012ms = euro2012.getTime();
var now = new Date();
var nowms = now.getTime();
var diff = euro2012ms - nowms;
var seconds = 1000;
var minutes = seconds*60;
var hours = minutes*60;
var days = hours*24;
var years = days*365;
var ddays = diff/days;
var dhours = (ddays - Math.round(ddays,1))*24;
var dminutes = (dhours - Math.round(dhours))*60;
var dseconds = (dminutes - Math.round(dminutes))*60;
document.getElementById("time").innerHTML='' + Math.round(ddays,1) +' days '+ Math.round(dhours,1) +' hours '+ Math.round(dminutes,1) +' minutes '+ Math.round(dseconds,1) + ' seconds remaining';
}
t=setInterval(timeto2012,500);
</script>
<div id="time"></div>
</body>
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
KOGI 可以解决您的问题:您应该使用
Math.floor
而不是Math.round
:当还剩 x 分钟 30 - 59 秒时,
(舍入完成后,x - Math.round(x))
相当于(x - (x + 1))
。小提琴:http://jsfiddle.net/YHktx/3/
KOGI has the answer to your problem: You should use
Math.floor
instead ofMath.round
:When there's x minutes and 30 - 59 seconds left, the
(x - Math.round(x))
would be equivalent to(x - (x + 1))
after the rounding was done.Fiddle: http://jsfiddle.net/YHktx/3/
这里有一些更好的计算给你(来自 Aleksi Yrttiaho 的 jsFiddle)
Here are some better calculations for you (derived from Aleksi Yrttiaho's jsFiddle)