我有一个时间计数器,工作120秒(即2分钟。虽然它工作正常,但我希望它应该以分钟和秒显示。这里的代码是JS FIDDLE < / p>
<span id="count">2:00</span>
<button type="submit" id="startClock" form="form1"value="Submit">Submit</button>
$('#startClock').click(function(){
var counter = 120;
setInterval(function() {
counter--;
if (counter >= 0) {
span = document.getElementById("count");
span.innerHTML = counter;
}
if (counter === 0) {
alert('sorry, out of time');
clearInterval(counter);
}
}, 1000);
});
我希望结果应该像这样显示
02:00
并且计时器应该继续减少
答案 0 :(得分:4)
使用此代码将秒转换为m:s
格式:
var str = parseInt(counter / 60) + ':' + (counter % 60);
完整代码:
$('#startClock').click(function() {
var counter = 120;
setInterval(function() {
counter--;
var str = parseInt(counter / 60) + ':' + (counter % 60);
if (counter >= 0) {
span = document.getElementById("count");
span.innerHTML = str;
}
if (counter === 0) {
alert('sorry, out of time');
clearInterval(counter);
}
}, 1000);
});
答案 1 :(得分:2)
您可以使用日期对象:
var d = new Date(counter * 1000);
span.innerHTML = d.getMinutes() + ':' + d.getSeconds();
答案 2 :(得分:1)
答案 3 :(得分:0)
使用此功能:
var
millisecToTimeStruct = function (ms) {
var d, h, m, s;
if (isNaN(ms)) {
return {};
}
d = ms / (1000 * 60 * 60 * 24);
h = (d - ~~d) * 24;
m = (h - ~~h) * 60;
s = (m - ~~m) * 60;
return {
d: ~~d,
h: ~~h,
m: ~~m,
s: ~~s
};
},
toFormattedStr = function (tStruct) {
var res = '';
if (typeof tStruct === 'object') {
res += tStruct.m + ':' + tStruct.s;
}
return res;
};
答案 4 :(得分:0)
你可以使用:
HTML:
<span id="count">02:00</span>
<button type="submit" id="startClock" form="form1" value="Submit">Submit</button>
JS:
$('#startClock').click(function () {
var counter = 120;
setInterval(function () {
counter--;
if (counter >= 0) {
span = document.getElementById("count");
var time =new Date(counter*1000);
var m = time.getMinutes();
m = m<10?'0'+m:m;
var s = time.getSeconds();
span.innerHTML = m+':'+s;
}
if (counter === 0) {
alert('sorry, out of time');
clearInterval(counter);
}
}, 1000);
});
这将更改格式为“02:00”的计时器。
答案 5 :(得分:0)
您可以更改
span.innerHTML = counter;
by:
var m = Math.floor(counter/60);
var s = counter-(m*60);
if(s<10){s="0"+s;}
span.innerHTML =m+":"+s;
它可以在0:01
这是你分叉和调整的小提琴:http://jsfiddle.net/6LL7ofyp/1/
答案 6 :(得分:0)
尝试(格式mm:ss
):
var span = document.querySelector("#count");
function countDown(counter){
var interval = setInterval(function(){
var minutes = ((counter / 60) | 0) + "";
var seconds = (counter % 60) + "";
var format = ""
+ new Array(3-minutes.length).join("0") + minutes
+ ':'
+ new Array(3-seconds.length).join("0") + seconds;
span.innerHTML = format;
counter--;
if(counter === 0){
clearInterval(interval);
alert('sorry, out of time')
}
},1e3)
}
countDown(120);
<span id="count"><span>