这是一款使用纯js实现电子时钟特效。该电子时钟可以显示时间,星期几,以及是上午还是下午。它使用简单,非常容易集成到项目中。
使用方法
在页面中引入电子时钟的样式文件main.css。
HTML结构
该电子时钟的基本HTML结构如下:
星期日
星期一
星期二
星期三
星期四
星期五
星期六
88
:
88
:
88
am
pm
JavaScript
该电子时钟通过下面的js代码来获取系统时间,并通过定时器来动态更新时间的显示。
window.onload = function(){
time();
ampm();
whatDay();
setInterval(function(){
time();
ampm();
whatDay();
}, 1000);
};
//gets current time and changes html to reflect it
function time(){
var date = new Date(),
hours = date.getHours(),
minutes = date.getMinutes(),
seconds = date.getSeconds();
//make clock a 12 hour clock instead of 24 hour clock
hours = (hours > 12) ? (hours - 12) : hours;
hours = (hours === 0) ? 12 : hours;
//invokes function to make sure number has at least two digits
hours = addZero(hours);
minutes = addZero(minutes);
seconds = addZero(seconds);
//changes the html to match results
document.getElementsByClassName('hours')[0].innerHTML = hours;
document.getElementsByClassName('minutes')[0].innerHTML = minutes;
document.getElementsByClassName('seconds')[0].innerHTML = seconds;
}
//turns single digit numbers to two digit numbers by placing a zero in front
function addZero (val){
return (val <= 9) ? ("0" + val) : val;
}
//lights up either am or pm on clock
function ampm(){
var date = new Date(),
hours = date.getHours(),
am = document.getElementsByClassName("am")[0].classList,
pm = document.getElementsByClassName("pm")[0].classList;
(hours >= 12) ? pm.add("light-on") : am.add("light-on");
(hours >= 12) ? am.remove("light-on") : pm.remove("light-on");
}
//lights up what day of the week it is
function whatDay(){
var date = new Date(),
currentDay = date.getDay(),
days = document.getElementsByClassName("day");
//iterates through all divs with a class of "day"
for (x in days){
//list of classes in current div
var classArr = days[x].classList;
(classArr !== undefined) && ((x == currentDay) ? classArr.add("light-on") : classArr.remove("light-on"));
}
}