javascript实现封装简单电子钟表组件代码
程序员文章站
2022-04-20 15:50:54
...
前几天想在我的个人主页上的右上角,添加一个可拖拽的电子钟表,然后趁这些天有点闲空,顺便简单复习下面向对象编程,所以花了点时间搞出来了,样子如下:
其实这个案例很简单,就是简单的利用了下Date类和定时器,当然写这个例子也只是为了稍稍复习下前端的知识,封装成了一个组件
代码如下:
(function (window, undefined) { function Time() { this.clock = null; this.date = new Date(); this.month = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December']; this.day = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Friday', 'Saturday']; this.str = '11:34 Tuesday30August '; } Time.prototype = { constructor: 'Time', init: function (selector) { this.createHTML(selector); this.getTime(); this.getDay(); }, createHTML: function (selector) { var elem = document.querySelector(selector); this.clock = elem; elem.innerHTML = this.str; }, getTime: function () { var clock = this.clock; var hour = clock.getElementsByClassName('cth_hour')[0]; var minute = clock.getElementsByClassName('cth_min')[0]; var point = clock.getElementsByClassName('cth_point')[0]; var date = this.date; var date_hour = this.addZoom(date.getHours()); //时 var date_minutes = this.addZoom(date.getMinutes()); //分 hour.innerHTML = date_hour; minute.innerHTML = date_minutes; var num = 0; var timer = setInterval(function () { if (num % 2 == 1) { point.style.visibility = 'visible'; } else { point.style.visibility = 'hidden'; } num++; }, 500); var This = this; var timer2 = setInterval(function () { var date = new Date(); hour.innerHTML = This.addZoom(date.getHours()); minute.innerHTML = This.addZoom(date.getMinutes()); }, 30000); }, getDay: function () { var clock = this.clock; var dates = clock.getElementsByClassName('cdm_date')[0]; var day = clock.getElementsByClassName('cdm_day')[0]; var month = clock.getElementsByClassName('cdm_month')[0]; var date = this.date; var date_day = date.getDay(); //星期 var date_date = date.getDate(); //日 var date_month = date.getMonth(); //月 dates.innerHTML = this.day[date_day]; day.innerHTML = this.addZoom(date_date); month.innerHTML = this.month[date_month * 1]; }, addZoom: function (para) { var str = ''; if (para < 10) { str = '0' + para; } else { str = para; } return str; } } DesktopTime = Time; })(window);
当然我是通过函数自执行的方式编写的函数,这样的好处就是避免了变量的重复,当然坏处就是,不好取函数里面的值,所以通过把Time类赋值给全局变量DesktopTime,将Time的prototype间接地给暴露出来,然后进行调用初始化。
相关推荐:
以上就是javascript实现封装简单电子钟表组件代码的详细内容,更多请关注其它相关文章!