javascript - Internet Explorer 中 Javascript 倒计时器上的 NaN

标签 javascript internet-explorer nan

我正在使用以下 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/

相关文章:

javascript - Javafx 调用 javascript 在 webview 中执行 java 函数不起作用

javascript - AJAX 成功不适用于 IE 和 Firefox

php - datepicker 回调在 IE 中不起作用

list - 如何从 Pandas 数据框中制作列表列表,跳过 nan 值

python - 向 Pandas describe() 方法添加范围

javascript - 无法使用 jQuery 的 "on click"事件监听器中包含的推送命令推送到全局范围内的数组

javascript - 如何在vue.js的组件中运行bootstrap的轮播间隔功能?

javascript - 这是为了我的目的而关闭的正确方法吗?

css - Internet Explorer 在应该悬停时隐藏 iframe

C 预处理器 : what is the motivation behind treating undefined macro as 0?