前端HTML+CSS3+JavaScript实现动态时钟
- 一、实现思路概述
- 二、源代码(包含HTML、CSS、JS)
- 三、图片资源与效果截图
- 1. 图片资源
- 2. 效果截图
一、实现思路概述
1. 通过HTML搭建基本时钟的页面结构(这里将时钟图片资源作为背景图)
2. 将时钟背景和时/分/秒图片进行CSS位置居中放置
3. 通过JS按以下步骤实现动态刷新时钟页面
- 获取时钟、时、分、秒标签
- 获取当前日期,并初始化时分秒变量
- 定义时钟的时、分、秒进位逻辑函数
- 初始化闹钟(设置时分秒指针旋转角度),显示闹钟
- 设置定时器间隔1秒刷新一次时、分、秒指针角度
二、源代码(包含HTML、CSS、JS)
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>数字时钟</title>
<style>
*{
padding: 0;
margin: 0;
}
#clock{
width: 600px;
height: 600px;
margin: 50px auto;
background-image: url("./images/clock.jpg");
position: relative;
display: none;
}
#hour, #minute, #second{
width: 30px;
height: 600px;
position: absolute;
left: 50%;
margin-left: -15px;
}
#hour{
background-image: url("./images/hour.png");
}
#minute{
background-image: url("./images/minute.png");
}
#second{
background-image: url("./images/second.png");
}
</style>
</head>
<body>
<div id="clock">
<div id="hour"></div>
<div id="minute"></div>
<div id="second"></div>
</div>
<script>
var clock = document.getElementById('clock');
var secondPointer = document.getElementById('second');
var minutePointer = document.getElementById('minute');
var hourPointer = document.getElementById('hour');
var now = new Date();
var second = now.getSeconds(), minute = now.getMinutes(), hour = now.getHours() % 12;
var secondAngle = 0, minuteAngle = 0, hourAngle = 0;
function setClock(){
second += 1;
if(second === 60){
second = 0;
minute += 1;
if(minute === 60){
minute = 0;
hour += 1;
if(hour === 12){
hour = 0;
}
}
}
secondAngle = second * 6;
minuteAngle = minute * 6 + second / 60;
hourAngle = hour * 30 + minute / 60 + second / 3600;
secondPointer.style.transform = `rotate(${secondAngle}deg)`;
minutePointer.style.transform = `rotate(${minuteAngle}deg)`;
hourPointer.style.transform = `rotate(${hourAngle}deg)`;
}
// 初始化时钟
setClock();
clock.style.display = 'block';
setInterval(setClock, 1000);
</script>
</body>
</html>
三、图片资源与效果截图
1. 图片资源