我正在使用以下 JavaScript 作为倒计时器,它在大多数浏览器中都运行良好,但我刚刚仔细检查了 Internet Explorer,但每个数字都显示为“NaN”。
任何人都可以帮助解释 IE 中出现问题的地方,没有将各个变量视为数字吗?
// Set the date we're counting down to
var countDownDate = new Date("2018-05-25 12:00:00").getTime();
// Update the count down every 1 second
var x = setInterval(function() {
// Get todays date and time
var now = new Date().getTime();
// Find the distance between now an 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);
if (days.toString().length < 2) {
days = "0" + days;
}
if (hours.toString().length < 2) {
hours = "0" + hours;
}
if (minutes.toString().length < 2) {
minutes = "0" + minutes;
}
if (seconds.toString().length < 2) {
seconds = "0" + seconds;
}
// Display the result in the element with id="countdown"
document.getElementById("countdown").innerHTML = days + " : " + hours + " : " +
minutes + " : " + seconds;
// If the count down is finished, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("countdown").innerHTML = "<a href='/register'>Countdown Expired</a>";
}
}, 1000);
<span id="countdown"></span>
最佳答案
MDN discourages the use of a string in the date constructor因为并非所有浏览器都以相同的方式实现这一点。
如果您确实想使用日期字符串,我建议使用第三方库,例如 momentjs解析这些字符串以确保它在每个浏览器中都有效。
关于javascript - Internet Explorer 中 Javascript 倒计时器上的 NaN,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49896708/