JavaScript代碼實現簡單日歷效果

本文實例為大傢分享瞭JavaScript實現簡單日歷效果的具體代碼,供大傢參考,具體內容如下

效果如下:

代碼:

<!DOCTYPE html>
<html lang="en">

<head>
 <meta charset="UTF-8">
 <meta http-equiv="X-UA-Compatible" content="IE=edge">
 <meta name="viewport" content="width=device-width, initial-scale=1.0">
 <title>Document</title>
 <style>
  * {
   margin: 0;
   padding: 0;
   box-sizing: border-box;
  }
  
  #box {
   width: 400px;
   height: 502px;
   border: 2px solid orange;
   margin: 50px auto;
   font-size: 48px;
   text-align: center;
  }
  
  #ym {
   height: 100px;
   line-height: 100px;
  }
  
  #d {
   height: 200px;
   line-height: 200px;
   background-color: orange;
   font-size: 72px;
  }
  
  #w {
   height: 100px;
   line-height: 100px;
  }
  
  #hms {
   height: 100px;
   line-height: 100px;
  }
 </style>
</head>

<body>
 <div id="box">
  <div id="ym"></div>
  <div id="d"></div>
  <div id="w"></div>
  <div id="hms"></div>

 </div>
 <script>
  //調用 getDateAndTime方法
  getDateAndTime();

  //啟動定時器,調用 getDateAndTime方法
  window.setInterval(getDateAndTime, 1000);

  function getDateAndTime() {


   //獲取系統當前的日期時間
   var date = new Date();

   //提取日期時間構成的元素
   var year = date.getFullYear();
   var month = date.getMonth() + 1;
   var day = date.getDate();
   var week = date.getDay();
   var hour = date.getHours();
   var minute = date.getMinutes();
   var second = date.getSeconds();

   //處理week的格式
   switch (week) {
    case 0:
     week = '星期日';
     break;
    case 1:
     week = '星期一';
     break;
    case 2:
     week = '星期二';
     break;
    case 3:
     week = '星期三';
     break;
    case 4:
     week = '星期四';
     break;
    case 5:
     week = '星期五';
     break;
    case 6:
     week = '星期六';
     break;


   }
   //定義函數處理時分秒的格式
   function formatHMS(time) {
    if (time < 10) {
     return '0' + time;
    } else {
     return time;
    }
   }

   //獲取頁面元素
   var ym = document.getElementById('ym');
   var d = document.getElementById('d');
   var w = document.getElementById('w');
   var hms = document.getElementById('hms');
   //將日期時間寫入到頁面
   ym.innerHTML = year + '年' + month + '月';
   d.innerHTML = day;
   w.innerHTML = week;
   hms.innerHTML = hour + '時' + minute + '分' + second + '秒';

  }
 </script>

</body>

</html>

以上就是本文的全部內容,希望對大傢的學習有所幫助,也希望大傢多多支持WalkonNet。