【温故而知新-Javascript】时间效果(显示当前时间、显示当前日期、显示页面停留时间、倒计时)

1.显示当前时间

<body onload="showtime()">
<div>当前时间:
<span id="clock"></span >
</div>
<script type="application/javascript">
function showtime()//创建函数
{
    var nowTime = new Date();//创建时间对象实例
    var hours = nowTime.getHours();//获取当前小时数
    var minutes = nowTime.getMinutes();//获取当前分钟数
    var seconds = nowTime.getSeconds();//获取当前秒数
    var timer = " "+((hours>12)?hours-12:hours);//将小时数质赋予变量timer
    timer +=((minutes<10)?"0:":":")+minutes;//将分钟数值赋予变量timer
    timer += ((seconds<10)?"0:":":")+seconds;//将秒数值赋予变量timer
    timer +=" "+((hours>12)?"pm":"am");//将字符am或pm赋予变量timer
    document.getElementById('clock').innerHTML =timer;
    setTimeout("showtime()",1000);
}
</script>
</body>

 

2.显示当前日期

<body onload="initArray()">
<div> <span id="todayIs"></span></div>
<script type="application/javascript">
function initArray()
{
    var today = new Date();
    var d = new Array(
    "星期日","星期一","星期二","星期三","星期四","星期五","星期六")
    //如果为2014年,getYear返回2014-1900=114,getFullYear返回2014
    var hh="<font color='#FBAE66' style='font-size:9pt;font-family:宋体'>今天是: "+
today.getFullYear()+""+(today.getMonth()+1)+""+today.getDate()+""+d[today.getDay()]+"</font>";
document.getElementById('todayIs').innerHTML = hh;
}
</script>
</body>

 

3.显示页面停留时间

<body>
<div>当前页面停留时间:<span id="yy004" >0时0分0秒</span></div>
<script type="text/javascript">
var sec =0;
var minu=0;
var hou=0;
//每隔一秒刷新一次
window.setTimeout("uupdate()",1000);

function uupdate()
{
    sec++;    
    if(sec==60)
    {
        sec =0;
        minu +=1;
    }
    if(minu==60)
    {
        minu=0;
        hou+=1;
    }
    var ss04 =hou+ ""+minu+""+sec+"";
    document.getElementById('yy004').innerHTML=ss04;
    window.setTimeout("uupdate()",1000);
}
</script>
</body>

 

4.倒计时

<body>
<div id="yy005"></div>
<script type="application/javascript">
var nowDay = new Date();
var yyear = nowDay.getFullYear()+1;
var timeDate = new Date(yyear+"-01-01");
var date = timeDate.getTime()-nowDay.getTime();//获取剩余时间
//将剩余时间转换为剩余天数
var time = Math.floor(date/(1000*60*60*24)); 
var show005="";
if(time>=0)
{
    show005 = "现在离"+yyear+"年元旦还有:<font color='red'><b>"+time+"</b></font>天";
    document.getElementById('yy005').innerHTML=show005;
    
}
</script>
</body>

 

来源:《HTML、CSS、Javascript网页制作从入门到精通》15.1章节

posted @ 2014-10-29 12:08  叶超Luka  阅读(5196)  评论(0编辑  收藏  举报