我正在尝试提前6天建立一个小时/分钟/秒的倒计时。
诀窍是,倒计时应该每天16:00重置,而不是24:00,并且应该以24小时格式显示日期。
日期应在时钟下方标明为“月(九月),日(13)”
这就是我的想法:
function ShowTimes() {
var now = new Date();
now.setDate(now.getDate() + 5)
if (now.getHours() > 14) {
var hrs = 39-now.getHours();
} else {
var hrs = 16-now.getHours();
}
var mins = 59-now.getMinutes();
var secs = 59-now.getSeconds();
var str = '';
str = now.toString();
str += '<br>'+hrs+' hours '+mins+' minutes '+secs+' seconds ';
document.getElementById('countdownToFour').innerHTML = str;
if (hrs < 0) {
hrs = 23-now.getHours();
now.setDate(now.getDate() + 6);
}
}
var _cntDown;
function StopTimes() {
clearInterval(_cntDown);
}
问题是我不知道如何将其设置为24小时以及如何将其重置为16.00而不是24.00。我好像已经提前6天设定了它,但我不太确定......
答案 0 :(得分:0)
因为很难理解你的代码,所以我创建了一个新的计数器:
<html>
<head>
<script type="text/javascript">
var counterIntervalVar;
var howManyDaysAhead = 0;
var finishHours = 16;
var finishMinutes = 0;
var finishSeconds = 0;
function ShowTimes()
{
var str = "";
var now = new Date();//Use current time as start time
//Creating the target time
var dayIncreasion = 1000 * 3600 * 24 * howManyDaysAhead;
var targetDateInMilliSeconds = now.getTime();
var targetDate = new Date(targetDateInMilliSeconds + dayIncreasion);
targetDate.setHours(finishHours);
targetDate.setMinutes(finishMinutes);
targetDate.setSeconds(finishSeconds);
targetDateInMilliSeconds = targetDate.getTime();
//Calculate and show the difference between current time and target time
var timeDifference = targetDateInMilliSeconds - now.getTime();
if (timeDifference >= 0)
{
var hrs = Math.floor(timeDifference / 1000 / 3600);
var mins = Math.floor(timeDifference / 1000 / 60) - (hrs * 60);
sec = Math.floor(timeDifference / 1000) - (hrs * 3600) - (mins * 60);
str += '<br>'+hrs+' hours '+mins+' minutes '+sec+' seconds ';
document.getElementById('countdownToFour').innerHTML = str;
} else {
howManyDaysAhead++;
}
//Give the 'if' query a realistic condition
if (str == 'x')
{
//Stop the loop
window.clearInterval(counterIntervalVar);
}
}
function initCountdown()
{
counterIntervalVar = window.setInterval("ShowTimes()",999);
}
</script>
</head>
<body onLoad="initCountdown()">
<div id="countdownToFour"></div>
</body>
</html>
希望这个例子适合你,或者至少引导你走正确的路。