<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<style>
.countdown {
width: 240px;
height: 305px;
text-align: center;
line-height: 1;
color: #fff;
background-color: brown;
overflow: hidden;
}
.countdown .next {
font-size: 16px;
margin: 25px 0 14px;
}
.countdown .title {
font-size: 33px;
}
.countdown .small {
font-size: 17px;
}
.countdown .clock {
width: 142px;
margin: 18px auto 0;
overflow: hidden;
}
.countdown .clock span,
.countdown .clock i {
display: block;
text-align: center;
line-height: 34px;
font-size: 23px;
float: left;
}
.countdown .clock span {
width: 34px;
height: 34px;
border-radius: 2px;
background-color: #303430;
}
.countdown .clock i {
width: 20px;
font-style: normal;
}
</style>
<body>
<div class="countdown">
<p class="next">今天是2024年1月19号</p>
<p class="title">下班倒计时</p>
<p class="clock">
<span id="hour">00</span>
<i>:</i>
<span id="minutes">25</span>
<i>:</i>
<span id="scond">20</span>
</p>
<p class="tips">18:00下班</p>
</div>
<script>
//随机颜色函数
//自定义一个随机颜色的函数
function getRandomColor(flag = true) {
console.log(flag);
//如果是true 则返回#ffffff
if (flag) {
let str = '#'
let arr = ['0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'a', 'b', 'c', 'd', 'e', 'f']
//利用for循环,随机抽6次 累加到Str里面
for (let i = 1; i <= 6; i++) {
//每次要随机从数组里面抽取一个
//random是数组的索引号 是随机的
let random = Math.floor(Math.random() * arr.length)
// str = str + arr[random]
str += arr[random]
}
return str
} else {
let button = document.getElementById("myButton");
button.addEventListener("click", () => {
div.style.backgroundColor = getRandomColor()
});
let r = Math.floor(Math.random() * 256)
let g = Math.floor(Math.random() * 256)
let b = Math.floor(Math.random() * 256)
console.log(`rgb(${r},${g},${b})`);
return `rgb(${r},${g},${b})`
}
}
//页面刷新随机颜色
const countdown = document.querySelector('.countdown')
countdown.style.backgroundColor = getRandomColor()
//函数封装 getCountTime
function getCountTime() {
//得到当前的时间戳
const now = +new Date()
//得到将来的时间戳
const last = +new Date('2024-5-1 18:00:00')
//将来的减去当前的 转换为秒数
const count = (last - now) / 1000
// h = parseInt(总秒数 / 60 / 60 % 24) //计算小时
// m = parseInt(总秒数 / 60 % 60) //计算分
// s = parseInt(总秒数 % 60) //计算当前秒数
//转换为时分秒
let d = parseInt(count / 60 / 60 / 24)
let h = parseInt(count / 60 / 60 % 24)
h = h < 10 ? '0' + h : h
let m = parseInt(count / 60 % 60)
m = m < 10 ? '0' + m : m
let s = parseInt(count % 60)
s = s < 10 ? '0' + s : s
//写到对应的盒子里面去
const hour = document.querySelector('#hour')
const minutes = document.querySelector('#minutes')
const scond = document.querySelector('#scond')
hour.innerHTML = h
minutes.innerHTML = m
scond.innerHTML = s
}
//先调用一次
getCountTime()
//开启定时器
setInterval(getCountTime, 1000)
</script>
</body>
</html>