做网页显示时间代码|js显示当前时间代码
做网页显示时间代码|js显示当前时间代码
今天做12580电子订票系统,用到了时间函数,总结一下:网页输出有alert、document.write 、innerHTML、innerText
获取时间函数:getYear()、getMonth()、getDate()、getHours()、getMinutes()、getSeconds()分别是:年、月、日、时、分、秒
第一种:alert()输出
<script language="javascript">
var current_time=new Date()
with(current_time)
{
var strDate=getYear()+"年";
strDate+=getMonth()+"月";
strDate+=getDate()+"月";
strDate+=getHours()+":";
strDate+=getMinutes()+":";
strDate+=getSeconds();
alert(strDate);
}
}
</script>
第二种:document.write输出
<script language="javascript">
var current_time=new Date()
with(current_time)
{
var strDate=getYear()+"年";
strDate+=getMonth()+"月";
strDate+=getDate()+"月";
strDate+=getHours()+":";
strDate+=getMinutes()+":";
strDate+=getSeconds();
document.write(strDate);
}
}
</script>
第三中:插入页面元素:
<script language="javascript">
var current_time=new Date()
with(current_time)
{
var strDate=getYear()+"年";
strDate+=getMonth()+"月";
strDate+=getDate()+"月";
strDate+=getHours()+":";
strDate+=getMinutes()+":";
strDate+=getSeconds();
document.getElementById('tm').innerHTML = "今天是"+strDate;//获取页面中id为tm的标签插入当前strDate值
}
}
</script>
分析:第三种输入方式,减少<body>页面元素,代码和页面可以做到分离。利于代码页面纯洁。
呵呵这里三种输出方式已经介绍完了,不过我们现在做完的输出时间是一个定值,不是和系统时间实时更新的,如果可以做到同步变化呢? 其实需要引用一个定时函数window.setInterval() 说明一下javascript严格区分大小写。
<script language="javascript">
function clock() //定义一个函数
{
var current_time=new Date()
with(current_time)
{
var strDate=getYear()+"年";
strDate+=getMonth()+"月";
strDate+=getDate()+"月";
strDate+=getHours()+":";
strDate+=getMinutes()+":";
strDate+=getSeconds();
alert(strDate);
//document.write(strDate);
document.getElementById('tm').innerHTML = "今天是"+strDate;//同上输入到页面当前值
}
}
window.setInterval("clock()",1000);// 定时1秒执行clock()函数,哈这下网页中的时间就可以做到实时更新了。试一下吧
</script>
上一条: CSS 网页制作什么是Sprites技术
下一条: 如何用thead和tbody网页制作表格