JS实现简单时钟效果

我会带着你远行 2022-01-25 15:39 444阅读 0赞

老师上课需要我们做一个时钟的小作业 ,我把它放在上面记录一下啦
表盘和时针我都是用的背景图的形式,然后绝对定位,通过调整left和top确定时针、分针、秒针的位置,transform-origin设置它们的旋转中心
具体效果:
在这里插入图片描述
HTML代码:

  1. <div class="box" id="box">
  2. <span></span>
  3. <span></span>
  4. <span></span>
  5. </div>

css代码:

  1. div.box{
  2. width: 620px;
  3. height: 620px;
  4. background: url("images/time.jpg") no-repeat;
  5. background-size: 100%;
  6. margin: 20px auto;
  7. position: relative;
  8. }
  9. div.box span{
  10. position: absolute;
  11. }
  12. div.box span:nth-child(3){
  13. width: 58px;
  14. height: 208px;
  15. background: url("images/time_1.png") no-repeat -8px -44px;
  16. left: calc(50% - 29px);
  17. top: 130px;
  18. transform-origin: center 174px;
  19. }
  20. div.box span:nth-child(2){
  21. width: 32px;
  22. height: 228px;
  23. background: url("images/time_1.png") no-repeat -72px -10px;
  24. left: calc(50% - 16px);
  25. top: 97px;
  26. transform-origin: center 205px;
  27. }
  28. div.box span:nth-child(1){
  29. width: 14px;
  30. height: 238px;
  31. background: url("images/time_1.png") no-repeat -131px -0px;
  32. left: calc(50% - 8px);
  33. top: 106px;
  34. transform-origin: center 198px;
  35. }

JS代码(设置一个定时器,每1秒执行一次,获取当前的时、分、秒,控制时针、分针、秒针的度数):

  1. var spans=document.querySelectorAll('div.box span');
  2. cur();
  3. setInterval(cur, 1000);
  4. function cur() {
  5. var now = new Date();
  6. var h = now.getHours();
  7. var m = now.getMinutes();
  8. var s = now.getSeconds();
  9. spans[2].style.transform="rotate("+h*30+"deg)";
  10. spans[1].style.transform="rotate("+m*6+"deg)";
  11. spans[0].style.transform="rotate("+s*6+"deg)";
  12. }

在这里插入图片描述在这里插入图片描述

发表评论

表情:
评论列表 (有 0 条评论,444人围观)

还没有评论,来说两句吧...

相关阅读

    相关 JS实现简单时钟效果

    老师上课需要我们做一个时钟的小作业 ,我把它放在上面记录一下啦 表盘和时针我都是用的背景图的形式,然后绝对定位,通过调整left和top确定时针、分针、秒针的位置,tran