javascript - 我希望输出分钟和秒像 09 :09

标签 javascript html css

// Set the date we're counting down to
var countDownDate = new Date();
countDownDate.setTime(countDownDate.getTime() + (30 * 60 * 1000));

// 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 and the count down date
  var distance = countDownDate - now;

  // Time calculations for days, hours, minutes and seconds
  var minutes = Math.floor((distance/1000/60)%60);
  var seconds = Math.floor((distance /1000) % 60);

  // Output the result in an element with id="demo"
  document.getElementById("demo").innerHTML =  minutes + "m " + seconds + "s ";

  // If the count down is over, write some text 
  if (distance < 0) {
    clearInterval(x);
    document.getElementById("demo").innerHTML = "EXPIRED";
  }
}, 1000);
<!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
p {
  text-align: center;
  font-size: 60px;
  margin-top: 0px;
}
</style>
</head>
<body>

<p id="demo"></p>

</body>
</html>

我想要以分钟为单位输出 2 个数字,以秒为单位输出 2 个数字,例如 09:06

我试过 slice(-2) 但它没有正常工作,所以我想知道其他选项来尝试

我是 js 和这些东西的新手

最佳答案

只需检查它是否小于 10,如果小于则添加前导 0:

var minutes = (Math.floor((distance/1000/60)%60)<10?'0':'') + Math.floor((distance/1000/60)%60);
var seconds = (Math.floor((distance /1000) % 60)<10?'0':'') + Math.floor((distance /1000) % 60);

关于javascript - 我希望输出分钟和秒像 09 :09,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56039185/

相关文章:

JavaScript 在鼠标悬停时隐藏另一个元素

javascript - JS 中数组表单元素验证

css - 是什么导致后续的.form-inline

html - 使用css并排对齐两个div,div包含点图标和文本

javascript float 栏未关闭 - 如何修复此 javascript 代码?

javascript - 检查Express Session是否过期

javascript - .NET 日期、Moment.js、UTC 和时区转换

css - CSS 中的中心和位置元素

html - 拖放区的视觉 HTML5 效果不错?

html - 缩放 HTML/CSS 以适应各种显示器,这可能吗?