【发布时间】:2024-01-16 07:15:01
【问题描述】:
我正在为我的网站进行倒计时。我们在每天 16:00 之前提供当天发货。我需要一个计数器来显示每天 16:00 的倒计时。 最终,我将修改代码,使其在周末根本不显示,但现在,我所需要的只是可以每天倒计时的东西。 16:00后消失,从00:00重新开始倒计时
下面是我目前的代码。
<?php
if (new DateTime() < new DateTime("16:00:00")) {
?>
<script type="text/javascript">
var CDown = function() {
this.state=0;// if initialized
this.counts=[];// array holding countdown date objects and id to print to {d:new Date(2013,11,18,18,54,36), id:"countbox1"}
this.interval=null;// setInterval object
}
CDown.prototype = {
init: function(){
this.state=1;
var self=this;
this.interval=window.setInterval(function(){self.tick();}, 1000);
},
add: function(date,id){
this.counts.push({d:date,id:id});
this.tick();
if(this.state==0) this.init();
},
expire: function(idxs){
for(var x in idxs) {
this.display(this.counts[idxs[x]], "Now!");
this.counts.splice(idxs[x], 1);
}
},
format: function(r){
var out="";
if(r.d != 0){out += r.d +" "+((r.d==1)?"day":"days")+", ";}
if(r.h != 0){out += r.h +" "+((r.h==1)?"hour":"hours")+", ";}
out += r.m +" "+((r.m==1)?"min":"mins")+", ";
out += r.s +" "+((r.s==1)?"sec":"secs")+", ";
return out.substr(0,out.length-2);
},
math: function(work){
var y=w=d=h=m=s=ms=0;
ms=(""+((work%1000)+1000)).substr(1,3);
work=Math.floor(work/1000);//kill the "milliseconds" so just secs
y=Math.floor(work/31536000);//years (no leapyear support)
w=Math.floor(work/604800);//weeks
d=Math.floor(work/86400);//days
work=work%86400;
h=Math.floor(work/3600);//hours
work=work%3600;
m=Math.floor(work/60);//minutes
work=work%60;
s=Math.floor(work);//seconds
return {y:y,w:w,d:d,h:h,m:m,s:s,ms:ms};
},
tick: function(){
var now=(new Date()).getTime(),
expired=[],cnt=0,amount=0;
if(this.counts)
for(var idx=0,n=this.counts.length; idx<n; ++idx){
cnt=this.counts[idx];
amount=cnt.d.getTime()-now;//calc milliseconds between dates
// if time is already past
if(amount<0){
expired.push(idx);
}
// date is still good
else{
this.display(cnt, this.format(this.math(amount)));
}
}
// deal with any expired
if(expired.length>0) this.expire(expired);
// if no active counts, stop updating
if(this.counts.length==0) window.clearTimeout(this.interval);
},
display: function(cnt,msg){
document.getElementById(cnt.id).innerHTML=msg;
}
};
window.onload=function(){
var cdown = new CDown();
cdown.add(new Date(2015,9,16,16,00,00), "countbox1");
};
</script>
<span style="font-size:30px;"><div id="countbox1"></div></span>
<?php } ?>
【问题讨论】:
-
很抱歉我无法正确格式化它,而且我认为它没有全部粘贴。我会把它放在网上的一个文件中并快速分享
-
您的问题是您必须始终打开特定的浏览器选项卡,因为如果有人关闭浏览器等,间隔将停止计数。我通常使用批处理文件重新打开页面,然后使用标准任务计划程序每天运行批处理文件。
-
为确保 Web 访问者看到正确的时间,请使用 PHP 计算剩余时间并将其提供给您的 JavaScript 代码(作为函数参数)。否则,访问者将看到基于他们本地机器时钟的时间(可能与您的公司时钟不同的分钟或小时)。如果这样做,请确保页面不会被缓存,否则访问者会看到过期的剩余时间。
-
我认为我的问题是那条线。 cdown.add(new Date(2015,9,16,16,00,00), "countbox1");如果我可以自动化“2015,9,16”来显示当天,那么我认为它会按照我的需要工作。
-
谢谢 Bobulous,我没有考虑页面缓存。
标签: javascript php timer counter countdown