我一直在尝试让这个计数器显示设定日期的剩余天数,然后在设定的日期显示一条消息,最后在该日期过后隐藏该消息。
这是我目前所拥有的......
// Set the date we're counting down to
var countDownDate = new Date("June 26, 2022 1:01:00").getTime();
// Update the count down every 1 second
var x = setInterval(function () {
// Get today's date and time
var now = new Date().getTime();
// Find the distance between now and the count down date
var distance = countDownDate - now;
// Time calculations for days, hours, minutes and seconds
var days = Math.floor(distance / (1000 * 60 * 60 * 24));
var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
var seconds = Math.floor((distance % (1000 * 60)) / 1000);
// Output the result in an element with id="countdown"
if (distance > 0) {
document.getElementById("countdown").innerHTML = days + " days until the June 30th, 2022";
} else if (distance == 0) {
document.getElementById("countdown").innerHTML = "Time To Vote";
} else {
document.getElementById("countdown").innerHTML = "EXPIRED";
}
}, 1000);
上面的脚本显示了剩余天数的倒计时和日期计数器结束时的“EXPIRED”,但它没有在设定的日期显示消息“Time to Vote”。 感谢您的帮助!
最佳答案
我对您所做的事情了解有限,而且声誉评分很小,但您是否也考虑了 new Date().getTime()
返回纪元毫秒?
这意味着,如果该日期的纪元毫秒与当前纪元毫秒不完全匹配,它将不会运行。
因此,日期的纪元可能是(示例)1000,但当前纪元可以是 1001,这是行不通的。
您可以尝试使用 new Date().getHours()
、new Date().getSeconds()
匹配各个时间单位等,以限制它应该检查多远。
编辑:我没有测试过,这可能是个糟糕的主意,但您可以通过除法和调用 .toFixed()
或使它成为一个字符串并使用 String.slice()
,然后比较它们
关于Javascript倒计时在指定日期显示、提醒和隐藏消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/72744889/