效果图:
时钟
一.分别获取时针、分针、秒针
const miao=document.querySelector('.second')
const fen=document.querySelector('.minute')
const shi=document.querySelector('.hour')
二.创建函数
function run(){
//获取当前的时间
const now=new Date();
const seconds=now.getSeconds();
const minutes=now.getMinutes();
const hours=now.getHours();
//分别定义时针分针秒针转的度数,然后让它们转动
const secondDegrees = (seconds / 60) * 360;
miao.style.transform = `rotate(${secondDegrees}deg)`;
const minuteDegrees = ((minutes + seconds / 60) / 60) * 360;
fen.style.transform = `rotate(${minuteDegrees}deg)`;
const hourDegrees = ((hours % 12 + minutes / 60) / 12) * 360;
shi.style.transform = `rotate(${hourDegrees}deg)`;
}
三.进行调用
run()
setInterval(run,1000)
setInterval
是 JavaScript 中的一个函数,用于按照指定的时间周期(以毫秒为单位)重复执行一个函数或代码片段。这个函数会返回一个区间 ID,这个 ID 可以用来通过clearInterval
函数停止间隔调用。
四.完整代码
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>钟</title>
<style>
.clock{
position:relative;
width:700px;
height: 700px;
}
.clock .bac{
width:700px ;
height:700px;
position: absolute;
}
.clock .hour{
position: absolute;
top: 40px;
left: 335px;
}
.clock .minute{
width: 35px;
height: 510px;
position: absolute;
top:88px;
left: 335px;
}
.second{
width: 35px;
height: 510px;
position: absolute;
top:88px;
left: 335px;
}
</style>
</head>
<body>
<div class="clock">
<img src="./clock.jpg" alt="" class="bac">
<img src="./minute.png" alt="" class="minute">
<img src="./hour.png" alt="" class="hour">
<img src="./second.png" alt="" class="second">
</div>
<script>
//1.分别获取时针分针秒针
const miao=document.querySelector('.second')
const fen=document.querySelector('.minute')
const shi=document.querySelector('.hour')
//2.创建函数
function run(){
//获取当前的时间
const now=new Date();
const seconds=now.getSeconds();
const minutes=now.getMinutes();
const hours=now.getHours();
//分别定义时针分针秒针转的度数,然后让它们转动
const secondDegrees = (seconds / 60) * 360;
miao.style.transform = `rotate(${secondDegrees}deg)`;
const minuteDegrees = ((minutes + seconds / 60) / 60) * 360;
fen.style.transform = `rotate(${minuteDegrees}deg)`;
const hourDegrees = ((hours % 12 + minutes / 60) / 12) * 360;
shi.style.transform = `rotate(${hourDegrees}deg)`;
}
//3.进行调用
run()
setInterval(run,1000)
</script>
</body>
</html>