您的位置:首页 > 其它

fgm实例练习笔记-3.8简易网页时钟

2017-07-13 12:07 417 查看
复习了 Date类型。创建一个日期对象
var now = new Date();
日期/时间方法,getHours() , getMinutes , getSeconds()

时间的更新引入了
setInterval(,1000);
函数。每1秒重新获取当前时间,并更新。

自己写的(没有实现的功能是当只有一位数字的时候前面自动补0):

window.onload = function(){
var inp = document.getElementsByTagName("input"); //不应该用input的,没有意义,用span就挺好
var change = function(){
var now = new Date();
inp[0].value = now.getHours();
inp[1].value = now.getMinutes();
inp[2].value = now.getSeconds();}

setInterval(change,1000);
}


原版:

window.onload = function ()
{
var oClock = document.getElementById("clock");

var aSpan = oClock.getElementsByTagName("span");

setInterval(getTimes, 1000);//每一秒调用一次getTimes函数

getTimes();
function getTimes ()
{
var oDate = new Date();//获取当前时间
var aDate = [oDate.getHours(), oDate.getMinutes(), oDate.getSeconds()];//数组aDate存储了时、分、秒

for (var i in aDate) aSpan[i].innerHTML = format(aDate[i])//依次写入时分秒
}

function format(a)
{
return a.toString().replace(/^(\d)$/, "0$1")  //format函数,为只有一位数字/^(\d)$/的,替换relace成前面添一个0。别忘了return新的值回去
}
}


改了一下自己的,补充了补0功能:

inp[0].value = ((now.getHours()).toString()).replace(/^(\d)$/,"0$1");
inp[1].value = ((now.getMinutes()).toString()).replace(/^(\d)$/,"0$1");
inp[2].value = ((now.getSeconds()).toString()).replace(/^(\d)$/,"0$1");//有点过于繁琐了,不如写个外部函数再调用
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: