JS原生实现时钟效果

如图

复制代码直接运行


<!DOCTYPE html>

<html lang="en">

<head>

  <meta charset="UTF-8">

  <meta http-equiv="X-UA-Compatible" content="IE=edge">

  <meta name="viewport" content="width=device-width, initial-scale=1.0">

  <title>timer</title>

</head>

<body>

  <div id="timer">

    <div id="h"></div>

    <div id="m"></div>

    <div id="s"></div>      

</div>

</body>

<style>

html,body{

  width: 100%;

  height: 100%;

  margin: 0 auto;

}

#timer {

  width: 600px;

  height: 600px;

  background-color: dimgray;

  border-radius: 50%;

  position: absolute;

  z-index: 1;

}

#h,#m,#s{

  width: 600px;

  height: 600px;

}

#h {

  background: url(./img/h.png) no-repeat center center;

  position: absolute;

  z-index: 2

}

#m {

  background: url(./img/m.png) no-repeat center center;

  position: absolute;

  z-index: 3;

}

#s {

  background: url(./img/s.png) no-repeat center center;

  position: absolute;

  z-index: 4;

}

</style>

<script>

  window.onload = function () {

    // 获取 DOM 元素

    var oh = document.getElementById("h");

    var om = document.getElementById("m");

    var os = document.getElementById("s");

    // 更新时间并渲染

    function go() {

      var time = new Date();

      console.log(time)

      var H = time.getHours() + time.getMinutes() / 60;

      console.log(H)

      var M = time.getMinutes();

      console.log(M)

      var S = time.getSeconds() + time.getMilliseconds() / 1000;

      console.log(S)

      os.style.transform = 'rotate(' + S * 6 + 'deg)';

      om.style.transform = 'rotate(' + M * 6 + 'deg)';

      oh.style.transform = 'rotate(' + H * 30 + 'deg)';

      //document.write("当前时间:"+H+":"+Mi+":"+S);

    }

    // 每隔 1s 更新并渲染

    go();

    setInterval(go, 1000);

  }

</script>

</html>

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容