Javascript倒计时显示,提醒和隐藏在指定日期的消息



我一直试图让这个计数器显示剩余的一天到一个设定的日期,然后,在设定的日期上显示一条消息,最后在日期过去后隐藏消息。

这是我到目前为止所做的…

// 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"日期计数器结束时,但它不显示消息"投票时间";在拍摄当天。谢谢你的帮助!

我的知识有限,对您所做的事情的评价也很小,但是您是否也考虑到new Date().getTime()返回epoch毫秒?

意味着,如果该日期的历元毫秒数与当前历元毫秒数不完全匹配,它将不会运行。

因此,日期的历元可能是(例如)1000,但当前的历元可能是1001,这将不起作用。

可以尝试使用new Date().getHours(),new Date().getSeconds()等来匹配单个时间单元,以限制它应该检查的距离。

编辑:我还没有测试过,这可能是一个可怕的想法,但是你可以通过划分和调用.toFixed()或使其成为字符串并使用String.slice()来删除两个epoch时间戳的最后5个左右数字,然后比较它们

你可以这样做

var countDownDate = new Date("June 26, 2022 0:00: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 (days > 0) {
const time = [hours, minutes, seconds].map(s => s.toString().padStart(2, '0')).join(':')
document.getElementById("countdown").innerHTML = `${days} days and ${time} until the June 30th, 2022`;
} else if (days === 0) {
document.getElementById("countdown").innerHTML = "Time To Vote";
} else {
document.getElementById("countdown").innerHTML = "EXPIRED";
}
}, 1000);
<div id="countdown"></div>

最新更新