原生js时钟(代码讲解)
程序员文章站
2023-11-15 23:34:04
话不多说,直接上代码。
话不多说,直接上代码。
<!doctype html> <html> <head> <meta charset="utf-8"> <title></title> <style> *{margin: 0;padding: 0; list-style: none;} .clock_box{width: 300px;height: 300px; margin: 100px auto; border-radius: 50%; border: 5px solid #000;position: relative;} .clock_dot{ position: absolute; top: 50%; left: 50%; margin: -5px 0 0 -5px; width: 10px;height: 10px; border-radius: 5px; background: #000;} .clock_dot p{position: absolute; top: -10px; left:2.5px; background: #000;transform-origin:2.5px 16px ; border-radius:0 0 10px 10px ;} .clock_second{width: 5px; height: 150px; } .clock_minute{width: 5px; height: 110px; } .clock_hour{width: 5px; height: 80px; } .clock_num{width:20px; text-align: center; height: 20px; font-size: 18px; font-weight: bold; color: #000;position: absolute; top: 0; left:50%;margin-left:-10px ; transform-origin:10px 150px;} </style> </head> <body> <p class="clock_box"> <p class="clock_dot"> <p class="clock_second"></p> <p class="clock_minute"></p> <p class="clock_hour"></p> </p> </p> </body> <script> class clock {//钟表初始化一系列操作 constructor(){ //声明初始化时分秒 this.secoud = 0; this.minute = 0; this.hour = 0; } init(){ for(var i=0;i<12;i++){ var p = document.createelement('p'); p.innerhtml = i+1; p.classname = "clock_num"; document.getelementsbyclassname('clock_box')[0].appendchild(p); } var numitem = document.getelementsbyclassname('clock_num'); for(var i=0;i<12;i++){ numitem[i].style.transform = "rotatez("+number(i*30+30)+"deg)"; } const date = new date(); this.second = date.getseconds(); this.minute = date.getminutes(); this.hour = date.gethours(); document.getelementsbyclassname('clock_second')[0].style.transform = "rotatez("+number(this.second*6+180)+"deg)"; document.getelementsbyclassname('clock_minute')[0].style.transform = "rotatez("+number(this.minute*6+180)+"deg)"; document.getelementsbyclassname('clock_hour')[0].style.transform = "rotatez("+number(this.hour*30+180)+"deg)"; let play = new play(clock); play.secoud() } } class play{//钟表计时 constructor(){ //声明动画开始时分秒 const date = new date(); this.s = date.getseconds(); this.m = date.getminutes(); this.h = date.gethours(); } secoud(){ const self = this;//防止指向冲突 settimeout(function() { requestanimationframe(function(){ if(self.s>59){//秒针转一圈 self.m++; self.s = 0; self.minute(); }else{ document.getelementsbyclassname('clock_second')[0].style.transform = "rotatez("+number(self.s*6+180)+"deg)"; self.s++; } self.secoud(); }) }, 1000); } minute(){ if(this.m>59){//分针转一圈 this.h++; this.m = 0; this.hour(); }else{ this.m++; document.getelementsbyclassname('clock_minute')[0].style.transform = "rotatez("+number(this.minute*6+180)+"deg)"; this.minute(); } } hour(){ document.getelementsbyclassname('clock_hour')[0].style.transform = "rotatez("+number(this.minute*6+180)+"deg)"; } } let clock = new clock(); clock.init(); </script> </html>
还有很多优化的地方。后续我会继续更新。
上一篇: PHP实现删除非站内外部链接实例代码
下一篇: LNMP系列教程之二 删除站点及域名绑定