<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
p{
width: 813px;
/* border: 1px solid red; */
font-size: 30px;
margin: 50px auto;
}
</style>
<body>
<script>
var num = 0;
function zero(num) { // 补 0 操作 让数字显示 01 而不是 1 好看一些
if (num < 10) {
return '0' + num
}
return num
}
setInterval(() => {
var now = Date.now(); // 当前时间
// console.log(now);
var old = new Date('2022 2 22').getTime(); // 未来时间
// console.log(old);
var and = (old - now) / 1000; // 时间差 秒
// console.log(and);
var day = Math.floor(and / 60 / 60 / 24); // 天
var h = Math.floor(and / 60 / 60); // 时
// console.log(h);
var m = Math.floor(and / 60 % 60); // 分
// console.log(m);
var s = Math.floor(and % 60); // 秒
// console.log(s);
document.body.innerHTML = `<p>距离2022年2月22日还有 ${zero(day)} 天 ${zero(h)} 小时 ${zero(m)} 分钟 ${zero(s)} 秒 </p>`
}, 16.6667);
</script>
</body>
</html>
JavaScript 时分秒时间代码(自动补零),超级简单的定时器 倒计时
最新推荐文章于 2024-03-31 09:44:29 发布