为了简单起见,假设我必须构建一个不断更新并显示每秒出生多少只小狗、小猫和老鼠的页面。就像计数器或计时器一样。
我还必须显示自早上 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 新手,所以请耐心等待。)
最佳答案
首先,setInterval()
的第二个参数以毫秒为单位。因此您希望该值为 1000,而不是 1。
假设每秒有 5 只小猫(我喜欢小猫!)。
今天早上 6 点以来有多少只小猫出生?
// Cache date object
var now = new Date();
// Give me milliseconds!
var six = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 6);
// Time now
var timeNow = now.getTime();
// Convert milliseconds to seconds
// Since it's in floating point, we'll round it.
var difference = Math.round((timeNow - six) / 1000);
// Woot, kittens!
var totalKittens = difference * 5;
本月初以来出生了多少只小猫?
同样的想法!我们将使用:
,而不是使用6
var monthBegin = new Date(now.getFullYear(), now.getMonth());
您可以省略这一天。暗示了月初。我怎么知道呢?
在文档中:
If at least two arguments are supplied, missing arguments are either set to 1 (if date is missing) or 0 for all others.
您应该了解有关 Date object 的更多信息.
关于javascript - 如何每秒将变量增加 (x) 个单位,然后将变量与 Date() 一起使用来确定自月初以来的单位数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20256126/