基本思想:首選要獲取要定時到的時間和現在的時間,通過new Date()能獲得當前的時間戳,也就是距離1970年1月1日0:0:0的時間差值,
![]()
![]()
new Date(引數)可以獲得距離傳入引數的時間戳
![]()
他倆之差除以一千(因為獲得的結果單位是毫秒,所以要除以一千得到的才是秒數)

![]()
然后再分別獲取天、時、分、秒


把得到的結果依次渲染到頁面上,呈現出最終的效果
<!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>
<style>
.time {
text-align: center;
color: #fff;
width: 234px;
height: 170px;
background: #000;
margin-right: 10px;
opacity: 0.5;
}
h2 {
margin-bottom: 40px;
}
span {
font-size: 32px;
}
</style>
</head>
<body>
<div class="time">
<h2>秒殺</h2>
<span>0</span>
<span>天</span>
<span>0</span>
<span>:</span>
<span>0</span>
<span>:</span>
<span>0</span>
</div>
<script src="https://cdn.bootcdn.net/ajax/libs/jquery/3.6.0/jquery.js"></script>
<script>
$(function () {
function time(t) {
let now = new Date();
let wei = new Date(t);
let time = Math.round((wei.getTime() - now.getTime()) / 1000);
let d = parseInt(time / 60 / 60 / 24);
let h = parseInt((time / 60 / 60) % 24);
let m = parseInt((time / 60) % 60);
let s = time % 60;
// console.log(d, h, m, s);
return {
day: d.toString().padStart(2, '0'),
hours: h.toString().padStart(2, '0'),
minutes: m.toString().padStart(2, '0'),
s: s.toString().padStart(2, '0'),
};
}
let x = time('2021-10-1 0:0:0');
$('.con-l .time span').eq(0).html(x.day);
$('.con-l .time span').eq(2).html(x.hours);
$('.con-l .time span').eq(4).html(x.minutes);
$('.con-l .time span').eq(6).html(x.s);
setInterval(function () {
let x = time('2021-10-1 0:0:0');
$(' .time span').eq(0).html(x.day);
$(' .time span').eq(2).html(x.hours);
$(' .time span').eq(4).html(x.minutes);
$(' .time span').eq(6).html(x.s);
}, 1000);
});
</script>
</body>
</html>
另:這里的padStart()方法,里面傳入兩個引數,第一個是總共要求的位數,第二個是補全所用的值,這里是padStart(2, '0'),當數為個位時,用0補全,當數值為兩位時,不影響結果,
轉載請註明出處,本文鏈接:https://www.uj5u.com/qianduan/289880.html
標籤:其他
上一篇:輸入6位數驗證碼的實作原理
