在小于10的数字前加上“0”?

时间:2015-01-08 18:37:01

标签: javascript jquery html

我有一个用HTML和Javascript制作的倒计时时钟。目前,当它加载时,由于具有动态宽度,文本将在屏幕上抖动。这是因为我试图强制它显示在页面的中心。我正在寻找一种方法来强制值始终是两位数。有没有办法(通过像if else语句之类的东西)我可以在所有小于10的值之前添加0?我尝试自己实现一些东西,但它没有用,所以我评论了它。这是代码:

<!DOCTYPE html>
<html>
<style>
body {
    background: #ffffff url("http://i.imgur.com/MelSn4S.png") no-repeat left top;
}
@font-face {
   font-family: sensation;
   src: url(arial);
}
div {
    color: white;
    font-family: arial;
    font-size: 60px;
    position: absolute;
    top: 50%;
    margin-left: 50%;
    margin-right: -50%;
    transform: translate(-50%, -50%)
}
</style>
<head>
<script type="text/javascript">
    var tenYearsInSeconds = 315360000;
    var yearInSeconds = 31536000;
    var monthInSeconds = 2592000;
    var dayInSeconds = 84600;
    var hourInSeconds = 3600;
    var minuteInSeconds = 60;

    var timer = window.setInterval(function() {countdown()}, 10);
    var runonce = true;

function countdown() {
    var temp = tenYearsInSeconds;
    var years = Math.floor(temp/yearInSeconds);

    temp = temp % yearInSeconds;
    var months = Math.floor(temp/monthInSeconds);

    temp = temp % monthInSeconds;
    var days = Math.floor(temp/dayInSeconds);

    temp = temp % dayInSeconds;
    var hours = Math.floor(temp/hourInSeconds);

    temp = temp % hourInSeconds;
    var minutes = Math.floor(temp/minuteInSeconds);


    document.getElementById('time').innerHTML = 
        "Years: " + years + 
        " Months: " + months + 
        " Days: " + days + 
        " Hours: " + hours + 
        " Minutes: " + minutes;
    tenYearsInSeconds = tenYearsInSeconds - 30000;

    if (tenYearsInSeconds <=0 && runonce) {
        tenYearsInSeconds = 0;
        runonce = false;
        countdown();
        clearInterval(timer);
    }

//if (years < 10) {
   //years = "0" + years;
//} 

}
</script>
</head>

<body>
<script type="text/javascript">
    countdown();
</script>
<div id="time"></div>
</body>
</html>

1 个答案:

答案 0 :(得分:1)

while (number.toString().length < desiredLength) {
   number = number.concat(0);
}

并把它放在前面,

   while (number.toString().length < desiredLength) {
      number = "0".concat(number);
   }