为了简单起见,可以说我必须建立一个不断更新并显示每秒每秒出生多少只小狗,小猫和老鼠的页面。像计数器或计时器。

我还必须显示自早上6点以来以及自月初以来已经出生了多少只小狗,小猫和老鼠。

我无法弄清楚的是如何使用Date()确定自早上6点以来和每月的星星以来已经出生了多少只小狗,小猫和老鼠,并且该数量不断更新。

的HTML

<section id="s01">
    <h1>if 3 puppies are born every second</h1>
    <b id="badge01" class="now">0</b> puppies have been born so far.<br>
    <b class="morning">?</b> puppies have been born since this 6 a.m. morning.<br>
    <b class="month">?</b> puppies have been born since the first of this month.
</section>

<section id="s02">
    <h1>if 5 kittens are born every second</h1>
    <b id="badge02" class="now">0</b> kittens have been born so far.<br>
    <b class="morning">?</b> kittens have been born since this 6 a.m. morning.<br>
    <b class="month">?</b> kittens have been born since the first of this month.
</section>

<section id="s03">
    <h1>if 7 rats are born every second</h1>
    <b id="badge03" class="now">0</b> rats have been born so far.<br>
    <b class="morning">?</b> rats have been born since this 6 a.m. morning.<br>
    <b class="month">?</b> rats have been born since the first of this month.
</section>


JS

var now = new Date();
var dayOfMonth = now.getDate();

setInterval(function () {
    // 3 puppies born every second
    $('#badge01').html(parseInt($('#badge01').html()) + 3);
    // 5 kittens born every second
    $('#badge02').html(parseInt($('#badge02').html()) + 5);
    // 7 rats born every second
    $('#badge03').html(parseInt($('#badge03').html()) + 7);
}, 1);


我的JSFiddle在这里-http://jsfiddle.net/gJy4x/6/(我是JS的新手,请多多包涵。)

最佳答案

我将从现在的时间开始,即早上6点和每月的第一天:

var start = new Date(),
    sixAM = new Date(start.getFullYear(), start.getMonth(), start.getDate(), 6),
    first = new Date(start.getFullYear(), start.getMonth(), 1);


然后,在您的时间间隔循环中查找自这些时间以来经过的秒数:

var now = new Date(),
    secondsFromStart = (now - start)/1000,
    secondsFromSixAM = (now - sixAM)/1000,
    secondsFromFirst = (now - first)/1000;


之后,您可以将值推入html(使用Math.floor向下舍入)。

参见更新的提琴-http://jsfiddle.net/gJy4x/7/

关于javascript - 如何每秒将变量增加(x)个单位,然后将变量与Date()结合使用以确定自本月初以来有多少个单位,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/20256126/

10-11 23:41