老師上課需要我們做一個(gè)時(shí)鐘的小作業(yè) ,我把它放在上面記錄一下啦
表盤和時(shí)針我都是用的背景圖的形式,然后絕對(duì)定位鸯屿,通過調(diào)整left和top確定時(shí)針、分針把敢、秒針的位置寄摆,transform-origin設(shè)置它們的旋轉(zhuǎn)中心
具體效果:
HTML代碼:
<div class="box" id="box">
<span></span>
<span></span>
<span></span>
</div>
css代碼:
div.box{
width: 620px;
height: 620px;
background: url("images/time.jpg") no-repeat;
background-size: 100%;
margin: 20px auto;
position: relative;
}
div.box span{
position: absolute;
}
div.box span:nth-child(3){
width: 58px;
height: 208px;
background: url("images/time_1.png") no-repeat -8px -44px;
left: calc(50% - 29px);
top: 130px;
transform-origin: center 174px;
}
div.box span:nth-child(2){
width: 32px;
height: 228px;
background: url("images/time_1.png") no-repeat -72px -10px;
left: calc(50% - 16px);
top: 97px;
transform-origin: center 205px;
}
div.box span:nth-child(1){
width: 14px;
height: 238px;
background: url("images/time_1.png") no-repeat -131px -0px;
left: calc(50% - 8px);
top: 106px;
transform-origin: center 198px;
}
JS代碼(設(shè)置一個(gè)定時(shí)器,每1秒執(zhí)行一次修赞,獲取當(dāng)前的時(shí)婶恼、分、秒榔组,控制時(shí)針熙尉、分針联逻、秒針的度數(shù)):
var spans=document.querySelectorAll('div.box span');
cur();
setInterval(cur, 1000);
function cur() {
var now = new Date();
var h = now.getHours();
var m = now.getMinutes();
var s = now.getSeconds();
spans[2].style.transform="rotate("+h*30+"deg)";
spans[1].style.transform="rotate("+m*6+"deg)";
spans[0].style.transform="rotate("+s*6+"deg)";
}