需要帮助调整Javascript的倒计时结果

时间:2011-05-31 17:30:44

标签: javascript width countdown

我正在进行此倒计时:http://apps.facebook.com/tjdcountdown/

我想为倒计时的每个结果(分钟,小时,天)添加一个特定的宽度,这样数字总是与下面的文字完全一致。

是否可以为每个结果创建一个变量,稍后在我的html代码中调用它们?

以下是倒计时的脚本:

<script type="text/javascript">

var myMonth = "<?= $myMonth ?>";
var myDay = "<?= $myDay ?>";
var myYear = "<?= $myYear ?>";
var myHour = "<?= $myHour ?>";
var myMin = "<?= $myMin ?>";

dateFuture1 = new Date(2013,03,26,14,15,00);

function GetCount(ddate,iid){

    dateNow = new Date();   //grab current date
    amount = ddate.getTime() - dateNow.getTime();   //calc milliseconds between dates
    delete dateNow;

    // if time is already past
    if(amount < 0){
        document.getElementById(iid).innerHTML="I'm now married!";
    }
    // else date is still good
    else{
        years=0;weeks=0;days=0;hours=0;mins=0;secs=0;out="";

        amount = Math.floor(amount/1000);//kill the "milliseconds" so just secs

        years=Math.floor(amount/31536000);//years (no leapyear support)
        amount=amount%31536000;

        weeks=Math.floor(amount/604800);//weeks
        amount=amount%604800;

        days=Math.floor(amount/86400);//days
        amount=amount%86400;

        hours=Math.floor(amount/3600);//hours
        amount=amount%3600;

        mins=Math.floor(amount/60);//minutes
        amount=amount%60;

        secs=Math.floor(amount);//seconds

        out += years +""+((years==1)?"":"")+"";
        out += weeks +""+((weeks==1)?"":"")+"";
        if(days != 0){out += days +""+((days==1)?"":"")+"";}
        if(hours != 0){out += hours +""+((hours==1)?"":"")+"";}
        out += mins +""+((mins==1)?"":"")+"";
        out += secs +""+((secs==1)?"":"")+", ";
        out = out.substr(0,out.length-2);
        document.getElementById(iid).innerHTML=out;
        setTimeout(function(){GetCount(ddate,iid)}, 1000);
    }
}

window.onload=function(){
    GetCount(dateFuture1, 'countbox1');
    //you can add additional countdowns here (just make sure you create dateFuture2 and countbox2 etc for each)
};
</script>

非常感谢您的帮助!

2 个答案:

答案 0 :(得分:1)

是的,你可以做到这一切。将每个数字放在它自己的div中,并将文本放在每个div中。确保文本居中不需要编码。

现在的主要问题是所有数字(年,周,日,小时等)被挤压成一个div(iid又名'countbox1'),当需要将它们分成自己的div时。

答案 1 :(得分:0)

我会确定数字的长度,然后使用该长度来确定合适的宽度。动态分配内存并不好(至少在我看来)。为了确定长度,我确信有更好的JS方法可以做到这一点,但一个简单的方法是保持除以10,直到值低于1并计算值的分数。

while(flag){
  i++;
  res = res/10
  if(res<1)
  flag=false;
}

// i would be your length
// should make this into a function prob