本文实例为大家分享了javascript实现简易数码时钟的具体代码,供大家参考,具体内容如下通过这个小例子复习一下Date对象的基本使用.
还可以用Date对象做定时器,计时器等等.效果如图:可以自己去找炫一点的图片来代替文字,原理都是一样,只是如果用图片代替文字,则定时切换图片即可.HTML代码:









CSS代码:
*{margin:0;padding:0;}
#clock{width:300px;height:150px;position: relative;margin:50px auto;background: #eeeeee;cursor: default;}
#clock p{margin-top:5px;width:300px;height: 40px;text-align: center;
font:italic bold 36px/40px arial,sans-serif;letter-spacing: 3px;color:blueviolet;}
*{margin:0;padding:0;}
#clock{width:300px;height:150px;position: relative;margin:50px auto;background: #eeeeee;cursor: default;}
#clock p{margin-top:5px;width:300px;height: 40px;text-align: center;
font:italic bold 36px/40px arial,sans-serif;letter-spacing: 3px;color:blueviolet;}JS代码:
window.onload = function ()
{
var oDiv = document.getElementById('clock');
var aP = oDiv.getElementsByTagName('p');
setInterval(clock,1000);
function clock()
{
var oDate = new Date(); //创建日期对象
var date = oDate.getFullYear()+'-'+ convert(oDate.getMonth()+1) +'-'+ convert(oDate.getDate());
var time = convert(oDate.getHours()) +':'+convert(oDate.getMinutes()) + ':' +convert(oDate.getSeconds());
aP[0].innerHTML = date;
aP[1].innerHTML = time;
aP[2].innerHTML = '星期' + convertWeek(oDate.getDay());
}
clock(); //加载完页面后立刻执行一次,不用等1秒后才显示
};

//把一位数字转换为两位字符串,补0
function convert(num)
{
return num < 9?'0'+num:''+num;
}
//把week转换为中文
function convertWeek(num)
{
return num==0?'日':num==1?'一':num==2?'二':num==3?'三':num==4?'四':num==5?'五':'六';
}
window.onload = function ()
{
var oDiv = document.getElementById('clock');
var aP = oDiv.getElementsByTagName('p');
setInterval(clock,1000);
function clock()
{
var oDate = new Date(); //创建日期对象
var date = oDate.getFullYear()+'-'+ convert(oDate.getMonth()+1) +'-'+ convert(oDate.getDate());
var time = convert(oDate.getHours()) +':'+convert(oDate.getMinutes()) + ':' +convert(oDate.getSeconds());
aP[0].innerHTML = date;
aP[1].innerHTML = time;
aP[2].innerHTML = '星期' + convertWeek(oDate.getDay());
}
clock(); //加载完页面后立刻执行一次,不用等1秒后才显示
};

//把一位数字转换为两位字符串,补0
function convert(num)
{
return num < 9?'0'+num:''+num;
}
//把week转换为中文
function convertWeek(num)
{
return num==0?'日':num==1?'一':num==2?'二':num==3?'三':num==4?'四':num==5?'五':'六';
}JavaScript时钟特效点击查看:JavaScript时钟特效专题JavaScript时钟特效专题以上就是本文的全部内容,希望对大家的学习有所帮助。