题目需求:
上方是简易的刻度时钟,下方是电子时钟,上下的时间需与北京时间实时对应。
演示:
刻度时钟
body部分:
<div id="tmer">
<div id="hour"></div>
<div id="min"></div>
<div id="sec"></div>
<div id="ta"></div>
</div>
<div class="box">
<span class="tit"><strong>北京时间</strong></span>
<p id="time"></p>
</div>
css部分:
<style>
*{
margin: 0;
padding: 0;
list-style: none;
}
#tmer{
width: 200px;
height: 200px;
border: 3px solid #000;
border-radius: 50%;
margin: 100px auto;
position: relative;
}
#ta{
width: 10px;
height: 10px;
background: #000;
border-radius: 50%;
position: absolute;
left: 95px;
top: 95px;
}
#hour{
width: 3px;
height: 60px;
background: rgb(0, 0, 0);
position: absolute;
left: 98px;
top: 35px;
transform-origin: center 65px;
}
#min{
width: 2px;
height: 85px;
background: #000;
position: absolute;
left: 98.5px;
top: 20px;
transform-origin: center 80px;
}
#sec{
width: 1px;
height: 100px;
background: rgb(0, 0, 0);
position: absolute;
left: 98.5px;
top: 20px;
transform-origin: center 80px;
}
.tit{
position: absolute;
font-size: 35px;
top: 350px;
left: 46.5%;
}
p {
font-size:50px;
font-weight: 600;
}
.box{
margin: 0px 860px;
}
</style>
JavaScript部分:
<script>
//设定总区块
window.onload=function(){
var otm=document.getElementById('tmer');
var oList=document.getElementById('list');
//时分秒设置
var oSec=document.getElementById('sec');
var oMin=document.getElementById('min');
var oHour=document.getElementById('hour');
function time(){
var date=new Date();
var s=date.getSeconds();
var m=date.getMinutes()+(s/60);
var h=date.getHours()+(m/60);
//deg绑定时间
oSec.style.transform='rotate('+s*6+'deg)';
oMin.style.transform='rotate('+m*6+'deg)';
oHour.style.transform='rotate('+h*30+'deg)';
}
time();
//设置时间间隔
setInterval(time,1000);
}
//获取北京时间
var getTime = function() {
var date = new Date();
var hour = date.getHours() < 10 ? '0' : date.getHours();
var min = date.getMinutes() < 10 ? '0' + date.getMinutes() : date.getMinutes();
var sec = date.getSeconds() < 10 ? '0' + date.getSeconds() : date.getSeconds();
var time = `${hour}:${min}:${sec}`;
//输出html格式
document.getElementById("time").innerHTML = time
}
setInterval(function(){
getTime()
}, 1000)
</script>
实现原理:利用deg
属性规范,设置滚动周期;使用定时器与transform:rotate
设置指针旋转频率,执行周期设定为一秒。利用date
获取时间,再利用定时器,频率每秒刷新一次时间