javascript实现时钟效果

效果展示:

时钟效果

初始效果:

初始效果

*{
    margin: 0;
    padding: 0;
  }
  li{
    list-style: none;
  }
  .clock{
    width: 202px;
    height: 202px;
    border:1px dashed #666;
    margin: 100px auto;
    position: relative;
  }
  .clock ul{
    width: 200px;
    height: 200px;
    border:1px solid #333;
    border-radius: 50% 50%;
    position: relative;
  }
  .clock ul li{
    width: 2px;
    height: 5px;
    background-color: #333;
    position: absolute;
    top: 0;
    left: 50%;
    margin-left: -1px;
    transform-origin: 50% 100px;
  }
  .clock ul li:nth-child(2){
    transform: rotate(6deg);
  }
  .clock ul li:nth-child(3){
    transform: rotate(12deg);
  }
  .clock ul li:nth-child(4){
    transform: rotate(18deg);
  }
  .clock ul li:nth-child(5){
    transform: rotate(24deg);
  }
  .clock ul li:nth-child(6){
    transform: rotate(30deg);
  }
  .clock ul li:nth-child(5n+1){
    height: 10px;
  }
  .clock div{
    position: absolute;
    top:100px;
    left: 50%;
    transform: translateX(-50%) rotate(180deg);
  }
  .clock .hour{
    width: 6px;
    height: 20px;
    background-color: red;
  }
  .clock .minute{
    width: 4px;
    height: 30px;
    background-color:blue;
  }
  .clock .second{
    width: 3px;
    height: 40px;
    background-color: green;
  }
  
</style>
<body>
    <div class="clock">
        <ul>
            <li></li>
            <li></li>
            <li></li>
            <li></li>
            <li></li>
            <li></li>
        </ul>
        <div class="hour"></div>
        <div class="minute"></div>
        <div class="second"></div>
    </div>
    <script>

    </script>
</body>

大盒子clock写出正方形虚框,ul标签包含60个时钟线,(动画首选css,JPU硬件加速。创建dom,用js)再用三个div标签代表时分秒时针。margin-left:-1px基准对准;
transform-origin:50% 100px;让每一个时针线有所倾斜。
.clock ul li:nth-child(5n+1) { height:10px;}每隔四个加长。
transform:translateX(-50%) rotate(180deg);让clock中每个div标签旋转180deg,旋转点绕x轴左移50%。

代码完善:

 .clock div{
    position: absolute;
    top:100px;
    left: 50%;
    transform: translateX(-50%) rotate(180deg);
    transform-origin: top;
  }
  .clock .hour{
    width: 6px;
    height: 20px;
    background-color: red;
    animation: run 216000s linear infinite;
  }
  .clock .minute{
    width: 4px;
    height: 30px;
    background-color:blue;
    animation: run 3600s linear infinite;
  }
  .clock .second{
    width: 3px;
    height: 40px;
    background-color: green;
    animation: run 60s linear infinite;
  }
  @keyframes run {
    0%{
      transform: translateX(-50%) rotate(180deg);
    }
    100%{
      transform: translateX(-50%) rotate(540deg);
    }
  }

基本的效果实现了。
有任何问题,非常希望您提出来!

发布了6 篇原创文章 · 获赞 1 · 访问量 184

猜你喜欢

转载自blog.csdn.net/caiyyu/article/details/94219418