当前位置:主页 > 网页前端 > JavaScript代码 >

JavaScript代码实现简单日历效果

时间:2022-06-23 11:38:52 | 栏目: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>

您可能感兴趣的文章:

相关文章