我的老板交给了我一段现有的 javascript,并要求对其进行修改 - 问题是,我根本不知道如何处理 javascript - 我们的后端开发人员意外退出,而我只是想帮忙。
我需要让这个倒计时器始终显示两位数(01 而不是 1)。我在这里搜索并尝试了一些类似的问题解决方案,但它们都针对单个问题,而且我根本没有运气使用 if else if 语句进行更改(部分是因为我的 js 理解和语法不好。)希望对于知道自己在做什么的人来说这是一个简单的修复!提前致谢。
<script>
// creating a reusable CountDownTimer class with TargetDate
/*
targetDate = Expiration date
displayCountDownOnElement = on what element you need the countdown displayed at.
hideOnExpire = on what element you need to hide when it expires.
*/
var CountDownTimer = function(targetDate, displayCountDownOnElement, hideOnExpire){
var target_date = new Date(targetDate).getTime();
var countdown = document.getElementById(displayCountDownOnElement);
var hideExpire = document.getElementById(hideOnExpire);
// variables for time units
var days, hours, minutes, seconds;
timer();
setInterval(timer, 1000);
function timer() {
// 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 + " : " + hours + " : "
+ minutes + " : " + seconds + " ";
if(seconds_left < 0) {
hideExpire.style.display = "none";
countdown.innerHTML = "";
}
}
}
// Sample Timer to Dec. 1, 2014 1:30:00 PM
var c = new CountDownTimer("Dec 1, 2014 1:30:00 PM GMT -0800","cyber-timer", "cyber-timer");
</script>
最佳答案
只需添加以下内容:
if(days < 10){days = "0" + days;}
if(hours < 10){hours = "0" + hours;}
if(minutes < 10){minutes = "0" + minutes;}
if(seconds < 10){seconds = "0" + seconds;}
在此之前:
// format countdown string + set tag value
countdown.innerHTML = days + " : " + hours + " : "
+ minutes + " : " + seconds + " ";
关于javascript 倒计时器 - 需要第二个数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26898378/