HTML/Html-Javascript/21-倒计时-秒杀倒计时.html

89 lines
1.9 KiB
HTML
Raw Normal View History

2023-05-01 19:37:40 +08:00
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
h1 {
text-align: center;
}
</style>
</head>
<body>
<h1 id="h1"></h1>
<script>
//秒杀倒计时
// 距离过年还剩多少天 时 秒
let h1Text =`距离过年还剩多少 00天 00时 00分 00秒`;
let h1DOM=document.querySelector("#h1");
//特定时间
let customDate = new Date("2023-01-22 00:00:00");
let interval =setInterval(()=>{
//当前时间
let newDate= new Date();
//拦截时间 ,以防时间不对
if(customDate<= newDate) return console.error("年已经过完了");
//准备
let d=`00`;
let h=`00`;
let m=`00`;
let s=`00`;
//做差
//以毫秒为单位的时差
let timeC = customDate-newDate;
let timeCM //计算后的时差
let dS =1000*60*60*24;//一天的毫秒
let hS=1000*60*60;//一小时的毫秒
let mS=1000*60;//一分钟的毫秒
let sS=1000;//一秒的毫秒
//计算倒计时
d=Math.floor( timeC/dS);
timeCM=timeC-d*dS; //不满一天的时间戳
h=Math.floor( timeCM/hS);
timeCM= timeCM-h*hS;//不满一小时的时间戳
m=Math.floor( timeCM/mS);
timeCM = timeCM-m*mS;//不满一分钟的时间戳
s=Math.floor( timeCM/sS);
h1DOM.innerText=`距离过年倒计时 ${twoNumber(d)}天 ${twoNumber(h)}时 ${twoNumber(m)}分 ${twoNumber(s)}秒`;
h1DOM.style.color=randomColorRGBA();
document.body.style.background=randomColorRGBA();
},1000)
//处理数
function twoNumber (num){
return num>=10 ? num: `0${num}`;
}
//随机色
function randomColorRGBA(params){
let r=Math.random()*255;
let g=Math.random()*255;
let b=Math.random()*255;
let a=Math.random();
return `rgba(${r},${g},${b},${a})`;
}
</script>
</body>
</html>