likes
comments
collection
share

纯原生 JS 实现倒计时!

作者站长头像
站长
· 阅读数 57

预览 Demo:count.xukaiyyds.cn

实现思路

目标时间 - 当前时间 = 剩余时间

当前时间

先计算当前时间用于显示证书打印日期,需要注意的是getMonth()的返回值需要加1才能得到实际的月份,因为它的索引值是从0到11。

另外getDate()getDay()要注意区分,后者是返回一周中的第几天(0代表周日)。

let current = new Date(); // 获取到当前中国标准时间
let year = current.getFullYear(); // 获取年份
let month = current.getMonth() + 1; // 获取月份
let date = current.getDate(); // 获取日份

可以再完善一下,给月份和日份加个判断,如果它们的长度为1就在前面加个0。

  if (String(month).length === 1) {
    month = "0" + month;
  }
  if (String(date).length === 1) {
    date = "0" + date;
  }

剩余时间

首先计算出剩余时间的毫秒数,再将毫秒分别转换为天、小时、分钟和秒。

let target = new Date("2023/10/16 21:45:32"); // 设置域名过期时间
let currentTime = current.getTime(); // 获取当前时间戳
let targetTime = target.getTime(); // 获取目标时间戳
let remainingTime = targetTime - currentTime; // 计算剩余时间戳

let days = Math.floor(remainingTime / (1000 * 60 * 60 * 24)); // 天
let hours = Math.floor((remainingTime % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60)); // 小时
let minutes = Math.floor((remainingTime % (1000 * 60 * 60)) / (1000 * 60)); // 分钟
let seconds = Math.floor((remainingTime % (1000 * 60)) / 1000); // 秒

出于美观考虑建议给它们前面都补个零,天数加不加都行。

  if (String(hours).length === 1) {
    hours = "0" + hours;
  }
  if (String(minutes).length === 1) {
    minutes = "0" + minutes;
  }
  if (String(seconds).length === 1) {
    seconds = "0" + seconds;
  }

更新时间

封装一个updateCountdown()的函数,将以上代码包裹在内。

function updateCountdown() {
...
}

开启setInterval计时器,设置每秒钟更新一次倒计时。

let timer = setInterval(updateCountdown, 1000);

当剩余时间为0时清除定时器,一定要放到updateCountdown()里面才行。

  if (remainingTime <= 0) {
    clearInterval(timer);
  }

最后,一个简单的倒计时大功告成!

转载自:https://juejin.cn/post/7276381076301283365
评论
请登录