Aza*_*lvi 0 javascript jquery countdown
我想要倒数计时器的格式,hh:mm:ss所以我使用这个代码它将秒转换成所需的格式,但当我倒计时它显示我NaN.你能告诉我我做错了吗这是代码
<div id="timer"></div>
Run Code Online (Sandbox Code Playgroud)
JS
String.prototype.toHHMMSS = function () {
var sec_num = parseInt(this, 10); // don't forget the second parm
var hours = Math.floor(sec_num / 3600);
var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
var seconds = sec_num - (hours * 3600) - (minutes * 60);
if (hours < 10) {
hours = "0" + hours;
}
if (minutes < 10) {
minutes = "0" + minutes;
}
if (seconds < 10) {
seconds = "0" + seconds;
}
var time = hours + ':' + minutes + ':' + seconds;
return time;
}
var count = '62';
count = count.toHHMMSS();
var counter = setInterval(timer, 1000);
function timer() {
count--;
if (count <= 0) {
clearInterval(counter);
return;
}
$('#timer').html(count);
}
Run Code Online (Sandbox Code Playgroud)
这是JsFiddle链接CountDown Timer
好吧,让我们来看看你的代码做了什么:
count为字符串值62.count等于字符串00:01:02count.嗯... count是一个字符串,你不能减少它.结果不是数字.好的,那么就这样,修复它的方法:
function formatTime(seconds) {
var h = Math.floor(seconds / 3600),
m = Math.floor(seconds / 60) % 60,
s = seconds % 60;
if (h < 10) h = "0" + h;
if (m < 10) m = "0" + m;
if (s < 10) s = "0" + s;
return h + ":" + m + ":" + s;
}
var count = 62;
var counter = setInterval(timer, 1000);
function timer() {
count--;
if (count < 0) return clearInterval(counter);
document.getElementById('timer').innerHTML = formatTime(count);
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4040 次 |
| 最近记录: |