簡體   English   中英

無法在我的倒數時鍾上顯示小於10的數字並顯示兩位數字

[英]Trouble getting numbers less than 10 to display with two digits on my countdown clock

因此,為了在網站上加載倒數時鍾,我找到了一些代碼來顯示一個。 實際上,不止一個例子。 我選了一個我能理解的東西,並在此過程中學到了更多的東西。 此代碼有效,但不會顯示兩位數小於10的數字(即,我希望7秒顯示為07秒)。

    // set the date we're counting down to
var target_date = new Date("May 16, 2014").getTime();

// variables for time units
var days, hours, minutes, seconds;

// get tag element
var countdown = document.getElementById("countdown");

// update the tag with id "countdown" every 1 second
setInterval(function () {

// find the amount of "seconds" between now and target
var current_date = new Date().getTime();
var seconds_left = (target_date - current_date) / 1000;

// do some time calculations
days = parseInt(seconds_left / 86400);
seconds_left = seconds_left % 86400;

hours = parseInt(seconds_left / 3600);
seconds_left = seconds_left % 3600;

minutes = parseInt(seconds_left / 60);
seconds = parseInt(seconds_left % 60);


// format countdown string + set tag value
countdown.innerHTML = days + " DAYS " + hours + ":"
+ minutes + ":" + seconds + " UNTIL DRAWING";


}, 1000);

我嘗試將時間變量設置為函數。 因此,我沒有上面的內容:

  seconds = function () {
   parseInt (seconds_left % 60);
   if (seconds_left % 60 < 10) {
   return "0" + seconds_left; }
   else return seconds_left % 60;
}

雖然沒有骰子。 我可能會嘗試的其他任何提示都將不勝感激。

如果數字小於十,只需在數字的開頭加上一個'0'即可:

countdown.innerHTML = (days < 10 ? '0' : '') + days + " DAYS " +
                      (hours < 10 ? '0' : '') + hours + ":" +
                      (minutes < 10 ? '0' : '') + minutes + ":" +
                      (seconds < 10 ? '0' : '') + seconds + " UNTIL DRAWING";

您的代碼幾乎可以,但是您確實需要在幾秒鍾后使用“()”來調用函數。 然后就是問題seconds()是另一個函數。

我重命名了該函數,將其移至interval函數中,並將秒數作為變量傳遞。

這是使其工作的一種方法:

//... your other code
hours = parseInt(seconds_left / 3600);
seconds_left = seconds_left % 3600;

minutes = parseInt(seconds_left / 60);
seconds = parseInt(seconds_left % 60);

var parseSeconds = function (seconds_left) {
   parseInt (seconds_left % 60);
   if (seconds_left % 60 < 10) {
   return "0" + seconds_left; }
   else return seconds_left % 60;
}

// format countdown string + set tag value
countdown.innerHTML = days + " DAYS " + hours + ":"
+ minutes + ":" + parseSeconds(seconds) + " UNTIL DRAWING";

}, 1000);

但是如果可以的話,更好的方法是使用moment.js 他們有很棒的簡單格式。

這是moment.js解決方案。 只需將所有代碼替換為此並導入moment.js

setInterval(function () {
    var countdown = document.getElementById("countdown");
    countdown.innerHTML = moment().format('MMMM Do YYYY, h:mm:ss a');    
}, 1000);

http://jsfiddle.net/7dxjK/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM