我正在使用下面的一段代碼在我的頁面上創建一個倒數計時器,它非常適用於所有日期信息硬編碼到「getSeconds」功能,我想這樣做,所以我可以在同一頁面上多次倒計時,我猜測意味着「getSeconds」函數將不得不被改爲接受參數,但我不太確定如何做到這一點,並認爲我會問這裏的專家他們的幫助。更改函數以使用參數而不是硬編碼值
<html>
<head>
<script type = "text/javascript">
var cday;
var timeInSecs;
var ticker;
function getSeconds() {
var now = new Date();
var nowtime = now.getTime(); // time now in milliseconds
var countdowntime = new Date(now.getFullYear(), now.getMonth(), now.getDate(), 0, 0, 0); // 16 hrs = 4 pm
// countdowntime - change time hh,mm,ss to whatever time required, e.g. 7,50,0 (0750)
var dy = 0; // Friday (day 5) - change for other days 0-6
var atime = countdowntime.getTime();
var diff = parseInt((atime - nowtime)/1000); // positive if date is in future
if (diff > 0) {
cday = dy - now.getDay();
} else {
cday = dy - now.getDay() - 1;
}
if (cday < 0) {
cday += 7;
} // aleady passed countdown time, so go for next week
if (diff <= 0) {
diff += (86400 * 7)
}
startTimer(diff);
}
function startTimer(secs) {
timeInSecs = parseInt(secs);
ticker = setInterval("tick()", 1000);
tick(); // to start counter display right away
}
function tick() {
var secs = timeInSecs;
if (secs > 0) {
timeInSecs--;
} else {
clearInterval(ticker); // stop counting at zero
getSeconds(); // and start all over again!
}
var days = Math.floor(secs/86400);
secs %= 86400;
var hours = Math.floor(secs/3600);
secs %= 3600;
var mins = Math.floor(secs/60);
secs %= 60;
var result = "Time remaining " + cday + ' day(s) ';
result += ((hours < 10) ? "0" : "") + hours + " hours " + ((mins < 10) ? "0" : "") + mins + " minutes " + ((secs < 10) ? "0" : "") + secs + " seconds";
document.getElementById("countdown").innerHTML = result;
}
</script>
</head>
<body onload = "getSeconds()">
<span id="countdown" style="font-size: 20; font-weight:bold;"> </span>
</body>
</html>
您是否可以將代碼減少到可能的最小數量,我們仍然可以看到該問題? –
更改爲只顯示有問題的功能 – avue
@JustinL .:沒有問題,他只是想知道他需要改變什麼。爲此,我們需要整個代碼,因爲它不僅包含'getSeconds'。 – Bergi