利用javascript實現動態顯示當前時間的效果代碼實例

很簡單的一個功能函數,實現方式很少言,用date()對象獲取到當前時間,而後用settimeout每隔1秒獲取最新的時間.
寫的過程當中碰到過一個小小的問題: 我最初的想法是用setinterval()每隔1秒獲取最新時間,但是能夠,但setinterval若是放在主函數內部,但致使內存泄漏(至於緣由, 暫時還沒想明白),後來在rocky的提醒下用settimeout()才解決內存泄漏問題css

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='上午&nbsp;'+h;
   }else if(h>12 && h<24){
    h-=12;
    h='下午&nbsp;'+fillzero(h);
   }else if(h==24){
    h='下午&nbsp;00';
   }
  }
  ev.innerhtml=y+'年'+m+'月'+d+'日 '+'&nbsp;'+w+'&nbsp;'+h+':'+i+':'+s;
  //每秒更新時間
  settimeout(arguments.callee,1000);
 })();
}

完整實例代碼html

<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>web

window.onload=function(){
 function nowtime(ev,type){
  /*
   * ev:顯示時間的元素
   * type:時間顯示模式.若傳入12則爲12小時制,不傳入則爲24小時制
   */
  //年月日時分秒www.3ppt.com
  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='上午&nbsp;'+h;
    }else if(h>12 && h<24){
     h-=12;
     h='下午&nbsp;'+fillzero(h);
    }else if(h==24){
     h='下午&nbsp;00';
    }
   }
   ev.innerhtml=y+'年'+m+'月'+d+'日 '+' '+w+'&nbsp;'+h+':'+i+':'+s;
   //每秒更新時間
   settimeout(arguments.callee,1000);
  })();
 }
 
 //24小時制調用
 nowtime(document.getelementbyid('time24'));
 //12小時制調用
 nowtime(document.getelementbyid('time12'),12);函數

}
</script>spa

<div id="demo">
 <h2 title="當前時間"><em>24小時制:</em><span id="time24"></span></h2>
 <h2 title="當前時間"><em>12小時制:</em><span id="time12"></span></h2>
</div>orm

相關文章
相關標籤/搜索