您好我的代码有问题。我已经尝试了几种方法,但没有成功在小时之前得到零等。我也检查了不同的主题,但没有成功。
var timestamp = (Date.now() + 1000 * 2 * 60 * 24 * 1) - Date.now();
timestamp /= 1000;
function component(x, v) {
return Math.floor(x / v);
}
/* last thing i tried but maybe it will help someone
Number.prototype.pad = function(size) {
var s = String(this);
while (s.length < (size || 2)) {s = "0" + s;}
return s;
};
*/
var $div = $('div');
setInterval(function () {
timestamp--;
var
hours = component(timestamp, 60 * 60),
minutes = component(timestamp, 60) % 60,
seconds = component(timestamp, 1) % 60;
$div.html(hours + ":" + minutes + ":" + seconds);
}, 1000);
DEMO:http://jsfiddle.net/5z7ahmze/1/
感谢您的时间。
答案 0 :(得分:3)
如果需要,您可以检查变量并添加0:
var comp = component(timestamp, 60 * 60);
var hour = comp < 10 ? '0' + comp : comp;
答案 1 :(得分:0)
也许这就是你想要的。正确?
好的,最后的答案。
var interval = setInterval(function () {
timestamp--;
function addZero (number) {
var zeroedNumber = (number < 10) ? 0 + "" + number : number;
return zeroedNumber;
}
var
hours = addZero(component(timestamp, 60 * 60)),
minutes = addZero(component(timestamp, 60) % 60),
seconds = addZero(component(timestamp, 1) % 60);
$div.html(hours + ":" + minutes + ":" + seconds);
//Below, i helped you with a "stop count" handler. (:
if(hours == 0 & minutes == 0 & seconds == 1){
clearInterval(interval);
}
}, 1000);
如果(小时或分钟或秒)是&lt;小时或分钟或秒10。
答案 2 :(得分:0)
您可以创建这样的功能
function pad(number, length) {
var str = '' + number;
while (str.length < length) {
str = '0' + str;
}
return str;
}
然后
$div.html(pad(hours, 2) + ":" + pad(minutes, 2) + ":" + pad(seconds, 2));
答案 3 :(得分:0)
如果您在数字上调用pad函数,我认为您的代码正常工作:
$div.html(hours.pad() + ":" + minutes.pad() + ":" + seconds.pad());