当前位置:编程学习 > JS >>

javascript 动态显示当前时间实现方法

很简单的一个功能函数,实现方式不多言,用date()对象获取到当前时间,然后用settimeout每隔1秒获取最新的时间.
写的过程中碰到过一个小小的问题: 我最初的想法是用setinterval()每隔1秒获取最新时间,可是可以,但setinterval如果放在主函数内部,但导致内存泄漏(至于原因,暂时还没想明白),后来在rocky的提醒下用settimeout()才解决内存泄漏问题

function nowtime(ev,type){
 /*
  * ev:显示时间的元素
  * type:时间显示模式.若传入12则为12小时制,不传入则为24小时制
  */
 //年月日时分秒
 var y,m,d,w,h,i,s;
 //月日时分秒为单位时前面补零
 function fillzero(v){
  if(v<10){v='0'+v;}
  return v;
 }
 (function(){
  var d=new date();
  var week=['星期天','星期一','星期二','星期三','星期四','星期五','星期六'];
  y=d.getfullyear();
  m=fillzero(d.getmonth()+1);
  d=fillzero(d.getdate());
  w=week[d.getday()];
  h=fillzero(d.gethours());
  i=fillzero(d.getminutes());
  s=fillzero(d.getseconds());
  //12小时制显示模式
  if(type && type==12){
   //若要显示更多时间类型诸如中午凌晨可在下面添加判断
   if(h<=12){
    h='上午 '+h;
   }else if(h>12 && h<24){
    h-=12;
    h='下午 '+fillzero(h);
   }else if(h==24){
    h='下午 00';
   }
  }
  ev.innerhtml=y+'年'+m+'月'+d+'日 '+' '+w+' '+h+':'+i+':'+s;
  //每秒更新时间
  settimeout(arguments.callee,1000);
 })();
}

完整实例代码

<style>
/*demo css教程*/
#demo h2{margin:20px 0 20px 20%;font:normal 24px/1.5 'comic sans ms';letter-spacing:2px;line-hight:2}
#demo h2 em{margin-right:12px;padding:0 7px;border-top-left-radius:8px;-webkit-border-top-left-radius:8px;-moz-border-radius-topleft:8px;background:#d2d9df;color:#000;font-family:5fae8f6f96c59ed1;letter-spacing:0}
#demo h2 span{text-shadow:1px 2px 3px #ccc}
</style>
<script>

window.onload=function(){
 function nowtime(ev,type){
  /*
   * ev:显示时间的元素
   * type:时间显示模式.若传入12则为12小时制,不传入则为24小时制
   */
  //年月日时分秒
  var y,m,d,w,h,i,s;
  //月日时分秒为单位时前面补零
  function fillzero(v){
   if(v<10){v='0'+v;}
   return v;
  }
  (function(){
   var d=new date();
   var week=['星期天','星期一','星期二','星期三','星期四','星期五','星期六']
   y=d.getfullyear();
   m=fillzero(d.getmonth()+1);
   d=fillzero(d.getdate());
   w=week[d.getday()];
   h=fillzero(d.gethours());
   i=fillzero(d.getminutes());
   s=fillzero(d.getseconds());
   //12小时制显示模式
   if(type && type==12){
    //若要显示更多时间类型诸如中午凌晨可在下面添加判断
    if(h<=12){
     h='上午 '+h;
    }else if(h>12 && h<24){
     h-=12;
     h='下午 '+fillzero(h);
    }else if(h==24){
     h='下午 00';
    }
   }
   ev.innerhtml=y+'年'+m+'月'+d+'日 '+' '+w+' '+h+':'+i+':'+s;
   //每秒更新时间
   settimeout(arguments.callee,1000);
  })();
 }
 
 //24小时制调用
 nowtime(document.getelementbyid('time24'));
 //12小时制调用
 nowtime(document.getelementbyid('time12'),12);

}
</script>

<div id="demo">
 <h2 title="当前时间"><em>24小时制:</em><span id="time24"></span></h2>
 <h2 title="当前时间"><em>12小时制:</em><span id="time12"></span></h2>
</div>

补充:网页制作,js教程 
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,