HTML
And on an article: Using jQuery and CSS3 to create digital clock the same HTML structure, but more a> date used to display the date and week.
<div id="clock" class="light">
<div class="display">
<div class="date"></div>
<div class="digits"></div>
</div>
</div>
jQuery
CSS code, refer to the previous article, the paper further ado, looking directly at the jQuery code.
First, we define the parameters used to call the class name of the array definition digital, the definition of weekday name, location, minutes and seconds of the definition.
$(function(){
var clock = $('#clock');
//define array 0-9
var digit_to_name = ['zero','one', 'two', 'three', 'four', 'five', 'six', 'seven', 'eight', 'nine'];
//weekdays
var weekday = ['Sun','Mon','Tus','Wen','Thu','Fri','Sat'];
var digits = {};
//hour min sec position
var positions = [
'h1', 'h2', ':', 'm1', 'm2', ':', 's1', 's2'
];
});
Then build a digital clock every minute. In the last article we are placed directly in the html structure html digital clock, and now we use jQuery to handle the clock display, to build a digital clock via append () method.
var 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 + '">');
}
digits[this] = pos;
digit_holder.append(pos);
}
});
Finally, we have to let the clock run up. Called once per second update_time () function, update_time () in, we will start with moment.js to format the time. Then according to the current time every minute, class attributes are set number of minutes and seconds, minutes and seconds that shows the current number. Then continue to use moment.js (shown in our article Use moment.js to manage the date and time easily) to format date and weeks, finally completed will move the digital clock, see the following code:
$(function(){
...
(function update_time(){
//call moment.js to format time
var now = moment().format("HHmmss");
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]]);
var date = moment().format("YYYY年MM月DD日");
var week = weekday[moment().format('d')];
$(".date").html(date + ' ' + week);
// run per sec
setTimeout(update_time, 1000);
})();
});