如何使用js实现可走动时间代码

JavaScript013

如何使用js实现可走动时间代码,第1张

一、js实现时间代码

<script type="text/javascript">

 function showtime(){

 var date=new Date()

var year=date.getFullYear()

var month=date.getMonth()+1

var day=date.getDay()

var hours=date.getHours()

var minutes=date.getMinutes()

var seconds=date.getSeconds()

        if(day==0){

        day=='日'

        }

        if(seconds<10){

seconds="0"+seconds

}

if (minutes<10) {

minutes="0"+minutes

}

if (hours<10) {

hours="0"+hours

}

var time=year+"/"+month+"/"+day+" "+hours+":"+minutes+":"+seconds

var o=document.getElementById("box")

    o.innerHTML=time

    setTimeout(showtime,1000)

   }

    showtime()

</script>

二、注意点

(1)用给变量赋予时间函数,月份要+1;

(2)将时间封装在函数中,好使用setTimeout(showtime,1000)

(3)var o=document.getElementById("box")()中写入想加到的div中的id选择符

(3)o.innerHTML=time是在HTML调用函数重要的语句

(4)该js必须放在想添加的div下面

网页中动态显示当前日期和时间是使用了js程序,方法如下:

将一下程序插入页面

<script language=Javascript>

  function time(){

    //获得显示时间的div

    t_div = document.getElementById('showtime')

   var now=new Date()

    //替换div内容

   t_div.innerHTML = "现在是"+now.getFullYear()

    +"年"+(now.getMonth()+1)+"月"+now.getDate()

    +"日"+now.getHours()+"时"+now.getMinutes()

    +"分"+now.getSeconds()+"秒"

    //等待一秒钟后调用time方法,由于settimeout在time方法内,所以可以无限调用

   setTimeout(time,1000)

  }

</script>

修改<body>为<body  onload="time()">以便js程序加载运行

插入<div id="showtime"></div>用以显示日期时间的容器。