我有一个脚本在工作,但是秒数只有一位数字。
我该如何解决2位数字的问题? 示例:4:01而不是4:1
倒计时必须是5分钟
JS:
setInterval(function() {
var d = new Date();
var seconds = d.getMinutes() * 60 + d.getSeconds(); //convet 00:00 to seconds for easier caculation
var fiveMin = 60 * 15; //five minutes is 300 seconds!
var timeleft = fiveMin - seconds % fiveMin; // let's say 01:30, then current seconds is 90, 90%300 = 90, then 300-90 = 210. That's the time left
var result = parseInt(timeleft / 60) + ':' + timeleft % 60; //formart seconds into 00:00
document.getElementById('test').innerHTML = result;
}, 500) //calling it every 0.5 second to do a count down
HTML:
<span id="test">6:00</span>
答案 0 :(得分:0)
当秒数为“ x”时,您可以使用
x = x < 10 ? "0" + x : x
以适合标准数字时间格式
在这种情况下,请将其应用于脚本结尾附近的timeleft % 60
。代替
var result = parseInt(timeleft / 60) + ':' + timeleft % 60;
你可以拥有
var min = parseInt(timeleft / 60);
var sec = timeleft % 60;
sec = parseInt(sec) < 10 ? "0" + sec : sec;
var result = min + ":" + sec;
答案 1 :(得分:0)
您可以使用padStart function
var result = parseInt(timeleft / 60) + ':' + (timeleft % 60).toString().padStart(2,'0');
setInterval(function() {
var d = new Date();
var seconds = d.getMinutes() * 60 + d.getSeconds(); //convet 00:00 to seconds for easier caculation
var fiveMin = 60 * 15; //five minutes is 300 seconds!
var timeleft = fiveMin - seconds % fiveMin; // let's say 01:30, then current seconds is 90, 90%300 = 90, then 300-90 = 210. That's the time left!
var result = parseInt(timeleft / 60) + ':' + (timeleft % 60).toString().padStart(2,'0'); //formart seconds into 00:00
document.getElementById('test').innerHTML = result;
}, 500) //calling it every 0.5 second to do a count down
<span id="test">6:00</span>