使用js和css做一个简单的钟表如图
1.png1.首先创立表盘div,然后子元素是三根指针
<div class="clock">
<div class="pointer hour"></div>
<div class="pointer min"></div>
<div class="pointer second"></div>
</div>
2.css样式代码
.clock{
position: absolute;
top: 50%;
left:50%;
transform: translate(-50%,-50%);
width: 400px;
height:400px;
background-image:url(images/dial.png);
background-repeat: no-repeat;
background-size:400px 400px;
opacity:0.5;
}
.pointer{
width: 10px;
height: 170px;
background-color: black;
position: absolute;
left: 195px;
top: 30px;
transform-origin: bottom center;
border-radius: 5px;
}
3.先用querySelector方法获取指针的dom
const hourhand = document.querySelector('.hour')
const minhand = document.querySelector('.min')
const secondhand = document.querySelector('.second')
4.利用new Data()获取当前时间然后根据时间各指针做出相对的角度旋转,且间隔为1000ms
function setDate(){
const tim = new Date()
//s
const second = tim.getSeconds()
const secondd = ((second / 60)*360)
secondhand.style.transform = `rotate(${secondd}deg)`;
//m
const min = tim.getMinutes();
const mind = ((min / 60)*360)
minhand.style.transform = `rotate(${mind}deg)`
//h
const hour = tim.getHours();
const hourd = ((hour/12)*360)
hourhand.style.transform = `rotate(${hourd}deg)`;
}
setInterval(setDate,1000)
setDate();
网友评论