js创建一个时钟

153 阅读3分钟

我正在参加「码上掘金挑战赛」详情请看:码上掘金挑战赛来了!

详细说明

用原生js+html+css实现一个时钟,下面来看下怎么实现这个时钟。
时钟是由四部分组成的:

  1. 一个大大的圆圈。
  2. 60个刻度,代表着走一圈的60秒。
  3. 时钟数字,没有数字鬼知道是几点。
  4. 指针:小时的指针、分钟的指针、秒钟的指针。

先画上一个大大的圆圈

<div class="circle"></div>

再给圆圈加上样式,让它变成一个真正的圆,变成圆的主要原因是 border-radius 属性,将它设置为50%,一个大大的⭕️就出来了。

.circle {
  width: 300px;
  height: 300px;
  border-radius: 50%;
  border: 1px solid black;
  position: relative;
}

接着画上刻度,由于刻度有60个,不可能去写60个div出来,这样代码会显得特别臃肿,可以用万能js来实现。有60个刻度,那么就循环创建60次刻度,创建完之后还需要给它加样式,每个刻度都是围绕着圆心旋转而成的。一个圆有360度,60个刻度,也就是说每个刻度之间距离旋转6度,那么就需要rotate属性。创建完一个就将它appendChild到scales里面,作为它的子元素。

// html代码
<ul class="scales"></ul>

// css代码
ul {
  list-style: none;
}

li {
  position: absolute;
  top: 50%;
  left: 50%;
  height: 10px;
  width: 1px;
  background-color: black;
}
.big {
  height: 20px;
  width: 2px;
}

// js代码
const scales = document.querySelector('.scales');
creatScale();
function creatScale() {
  for( let i=0; i<60; i++) {
    const kedu = i * 6;
    const length = i % 5 === 0 ? 16 : 10;
    const li = document.createElement('li');
    i % 5 === 0 ? li.classList.add('big') : '';
    li.style.transform = `translate(-50%, -50%)  rotate(${kedu}deg) translateY(-${150 - length * 0.5}px)`;
    scales.appendChild(li);
  }
}

时钟的数字不多,只有四个,所以我们可以全部都用html画

<span class="num1">12</span>
<span class="num2">3</span>
<span class="num3">6</span>
<span class="num4">9</span>

时钟的数字不需要旋转,可以直接使用定位放到相对应的位置上,我这里圆圈的宽度是300,圆的中心点大概在150左右,具体的位置可以慢慢调。

.num1 {
  position: absolute;
  top: 17pxpx;
  left: 141px;
}
.num2 {
  position: absolute;
  left: 270px;
  top: 138px;
}
.num3 {
  position: absolute;
  left: 145px;
  top: 262px;
}
.num4 {
  position: absolute;
  left: 20px;
  top: 138px;
}

剩下的就三个指针了,三个指针可以用html画出来,并加上样式。但是指针是会动的,秒针每一秒就需要走一个刻度,分钟每一秒就需要走1/60刻度,时钟每一秒就需要走1/360刻度。每次走的时候指针的位置都需要有所改变,我们只要通过计算,改变它的rotate属性就可以。我们可以使用计时器来实现

// html代码
<div id="hour"></div>
<div id="min"></div>
<div id="second"></div>

//css 代码
#second{
    width: 1px;
    height: 110px;
    background-color: red;
    transform: scaleY(1);
    position: absolute;
    left: 149px;
    top: 40px;
    transform-origin: bottom; 
}
#min{
    width: 2px;
    height: 80px;
    background-color: gray;
    transform: scaleY(1);
    position: absolute;
    left: 149px;
    top: 70px;
    transform-origin: bottom;
}
#hour{
    width: 3px;
    height: 70px;
    background-color: black;
    transform: scaleY(1);
    position: absolute;
    left: 149px;
    top: 80px;
    transform-origin: bottom;
}

// js代码
setInterval( function() {
    let s=document.getElementById("second");
    let m=document.getElementById("min");
    let h=document.getElementById("hour");

    //获取时间。
    let snum = new Date().getSeconds();
    let mnum = new Date().getMinutes()+snum/60;
    let hnum = new Date().getHours()+mnum/60;
      
    s.style.transform=`rotate(${snum*6}deg)`;
    m.style.transform=`rotate(${mnum*6}deg)`
    h.style.transform=`rotate(${hnum*30}deg)`
}, 100)

码上掘金的代码展示