制作简易时钟

212 阅读1分钟

效果图

利用html+css+js制作简易时钟 image.png

html部分

<div class="clock">
        <div class="hour">
            <div class="hr" id="hr"></div>
        </div>
        <div class="min">
            <div class="mn" id="mn"></div>
        </div>
        <div class="sec">
            <div class="sc" id="sc"></div>
        </div>
    </div>

css部分

*{
    margin: 0;
    padding: 0;
}
body{
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 100vh;
    background: white;
}
.clock{
    width: 350px;
    height: 350px;
    /* 利用flex布局,将时针,分针,秒针定位到钟的水平垂直居中的位置 */
    display: flex;
    justify-content: center;
    align-items: center;
    background: url(./clock.png);
    background-size: cover;
    border: 4px solid pink;
    border-radius: 50%;
}
/* 利用伪元素在钟的中心添加一个点 */
.clock:before{
    content: '';
    position: absolute;
    width: 15px;
    height: 15px;
    background-color: pink;
    border-radius: 50%;
    z-index: 100;
}
.clock .hour, .clock .min, .clock .sec{
    position: absolute;
}
.clock .hour, .hr{
    width: 160px;
    height: 160px;
}
.clock .min, .mn{
    width: 190px;
    height: 190px;
}
.clock .sec, .sc{
    width: 230px;
    height: 230px;
}
.hr, .mn, .sc{
    display: flex;
    justify-content: center;
    position: absolute;
    border-radius: 50%;
}
.hr::before{
    content: '';
    position: absolute;
    width: 8px;
    height: 80px;
    background-color: pink;
    z-index: 10;
    border-radius: 6px 6px 0 0 ;
}
.mn::before{
    content: '';
    position: absolute;
    width: 4px;
    height: 90px;
    background-color: black;
    z-index: 11;
    border-radius: 6px 6px 0 0;
}
.sc::before{
    content: '';
    position: absolute;
    width: 2px;
    height: 150px;
    background-color: red;
    z-index: 12;
    border-radius: 6px 6px 0 0;
}

js部分

利用定时器 1秒钟动一下让秒针转动

const deg = 6;
     const hr = document.querySelector('#hr');
     const mn = document.querySelector('#mn');
     const sc = document.querySelector('#sc');

     setInterval(() =>{
         let day = new Date();
         
         let h = day.getHours() *30;
         let m = day.getMinutes() * deg;
         let s = day.getSeconds() * deg;

         
         hr.style.transform= `rotateZ(${h + m/12}deg)`;
         mn.style.transform=`rotateZ(${m}deg)`;
         sc.style.transform=`rotateZ(${s}deg)`;
     },1000)

时针不是一个小时动一次,分针一小时动360°,时针一小时30°,所以时针的度数为分针/12°