如何用jQuery和CSS3制作数字时钟[译]
数字说明
它们完全用CSS样式渲染且默认设置为 opacity:0 。定义在它们父div上的样式将决定它们的可见性。下面是数字“0”的CSS:
黑色主题
jQuery 代码要想要时钟工作,我们将使用jQuery生成每个数字的标签,并且设置一个定时器每秒钟更新一次样式,为了更简单,我们使用moment.js 库(快速开始) 来补偿JavaScript原生日期和时间方法的缺陷。
assets/js/script.js$(function(){// Cache some selectorsvar clock = $('#clock'),alarm = clock.find('.alarm'),ampm = clock.find('.ampm');// Map digits to their names (this will be an array)var digit_to_name = 'zero one two three four five six seven eight nine'.split(' ');// This object will hold the digit elementsvar digits = {};// Positions for the hours, minutes, and secondsvar positions = ['h1', 'h2', ':', 'm1', 'm2', ':', 's1', 's2'];// Generate the digits with the needed markup,// and add them to the clockvar digit_holder = clock.find('.digits');$.each(positions, function(){if(this == ':'){digit_holder.append('<div class="dots">');}else{var pos = $('<div>');for(var i=1; i<8; i++){pos.append('<span class="d' + i + '">');}// Set the digits as key:value pairs in the digits objectdigits[this] = pos;// Add the digit elements to the pagedigit_holder.append(pos);}});// Add the weekday namesvar weekday_names = 'MON TUE WED THU FRI SAT SUN'.split(' '),weekday_holder = clock.find('.weekdays');$.each(weekday_names, function(){weekday_holder.append('<span>' + this + '</span>');});var weekdays = clock.find('.weekdays span');// Run a timer every second and update the clock(function update_time(){// Use moment.js to output the current time as a string// hh is for the hours in 12-hour format,// mm - minutes, ss-seconds (all with leading zeroes),// d is for day of week and A is for AM/PMvar now = moment().format("hhmmssdA");digits.h1.attr('class', digit_to_name[now[0]]);digits.h2.attr('class', digit_to_name[now[1]]);digits.m1.attr('class', digit_to_name[now[2]]);digits.m2.attr('class', digit_to_name[now[3]]);digits.s1.attr('class', digit_to_name[now[4]]);digits.s2.attr('class', digit_to_name[now[5]]);// The library returns Sunday as the first day of the week.// Stupid, I know. Lets shift all the days one position down, // and make Sunday lastvar dow = now[6];dow--;// Sunday!if(dow < 0){// Make it lastdow = 6;}// Mark the active day of the weekweekdays.removeClass('active').eq(dow).addClass('active');// Set the am/pm text:ampm.text(now[7]+now[8]);// Schedule this function to be run again in 1 secsetTimeout(update_time, 1000);})();// Switch the theme$('a.button').click(function(){clock.toggleClass('light dark');});});?
这里最重要的代码部分就是
update_time方法,在它里面,我们获取到当前日期作为一个字符串,并且使用它来填充时钟元素并且给数字设置正确的样式。?
有了这些我们的数字时钟已经做好了准备!
下周保持收听啊,我们将要为设置闹铃添加方法并且用HTML5的audio来播放。
E文链接:http://tutorialzine.com/2013/06/digital-clock/
译文链接:http://www.woiweb.net/make-digital-clock-with-jquery-and-css.html
?