做了一个小时钟,本来想找ios的时钟模型,但是找不到就只能随便百度了一个。直接上代码吧。
1.html布局:
<body>
<div class="box">
<div class="clock">
<div id="hours"></div>
<div id="minutes"></div>
<div id="seconds"></div>
</div>
</div>
</body>
布局比较简单。一眼就能看出来就不多说了。
2.css样式
<style>
*{margin: 0;padding: 0;list-style: none}
html{font-size: 12px}
/*用了最近刚刚看的flex盒子布局,感觉挺方便的*/
.box{
width: 35rem;
height: 38rem;
background: rgb(205,205,205);
border-radius: 1rem;
display: flex;/*弹性盒子布局,xy轴居中*/
justify-content: center;
align-items: center;
}
.clock{/*背景图层*/
width: 30rem;
height: 30rem;
background: #fff url("img/time.jpg")no-repeat center;
background-size:140%;
border-radius:50%;
position: relative;
}
/*三个指针都用设置默认初始位置是12点*/
#hours{
width: 3%;
height: 25%;
background: #000;
position: absolute;
transform-origin: 50% 100%;
top: 25%;
left: 48.5%;
}
#minutes{
width: 3%;
height: 45%;
background: #000;
position: absolute;
transform-origin: 50% 100%;
top: 5%;
left: 48.5%;
}
#seconds{
width: 1%;
height: 48%;
position: absolute;
background: #f00;
transform-origin: 50% 90%;
top: 7%;
left: 49.5%;
z-index: 8;
border-radius: 0 120% 120% 0;
}
</style>
3.js代码
比较简单明了
function timeChange(){
//首先获取到时间,然后再获取元素
var nowTime = new Date(),
hour = nowTime.getHours(),
minute = nowTime.getMinutes(),
second = nowTime.getSeconds(),
hourHand = document.getElementById("hours"),
minuteHand = document.getElementById("minutes"),
secondHand = document.getElementById("seconds");
//计算角度,因为我初始都是12点,所以比较简单
hourHand.style.transform = "rotate("+(hour * 30)+"deg)";
minuteHand.style.transform = "rotate("+(minute * 6)+"deg)";
secondHand.style.transform = "rotate("+(second * 6)+"deg)";
//设置定时器
var timer = setTimeout(function(){
timeChange();
},1000)
};
//最后在加载执行函数
window.onload = function(){
timeChange()
};
网友评论