前幾天想在我的個人主頁上的右上角,添加一個可拖曳的電子鐘錶,然後趁這些天有點閒空,順便簡單複習下面向對象編程,所以花了點時間搞出來了,樣子如下:
其實這個案例很簡單,就是簡單的利用了下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實作封裝簡單電子鐘錶組件程式碼的詳細內容。更多資訊請關注PHP中文網其他相關文章!