欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

简易 javascript 日历

程序员文章站 2023-12-21 17:29:22
...

简易 javascript 日历

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <head>
  4. <meta charset="UTF-8">
  5. <title>Title</title>
  6. <style>
  7. body, ul, li {
  8. margin: 0;
  9. padding: 0;
  10. box-sizing: border-box;
  11. }
  12. .calendar {
  13. margin: 10px auto;
  14. border: 1px solid;
  15. width: 21rem;
  16. }
  17. .calendar > .header {
  18. display: flex;
  19. justify-content: space-between;
  20. align-items: center;
  21. margin: .5rem;
  22. }
  23. .calendar > .header > .middle {
  24. text-align: center;
  25. }
  26. .calendar > ul {
  27. list-style: none;
  28. display: flex;
  29. margin-bottom: .5rem;
  30. }
  31. .calendar > ul > li {
  32. flex-basis: 3rem;
  33. padding: .5rem;
  34. text-align: center;
  35. }
  36. .calendar > ul.week {
  37. background-color: darkgray;
  38. }
  39. .calendar > ul.date {
  40. flex-wrap: wrap;
  41. }
  42. .calendar > ul.date > li.active {
  43. color: red;
  44. }
  45. </style>
  46. </head>
  47. <body>
  48. <div class="calendar">
  49. <div class="header">
  50. <a class="prev" href="javascript:" title="上一月">上一月</a>
  51. <div class="middle">
  52. <div class="year"></div>
  53. <div class="month"></div>
  54. </div>
  55. <a class="next" href="javascript:" title="下一月">下一月</a>
  56. </div>
  57. <ul class="week">
  58. <li></li>
  59. <li></li>
  60. <li></li>
  61. <li></li>
  62. <li></li>
  63. <li></li>
  64. <li></li>
  65. </ul>
  66. <ul class="date"></ul>
  67. </div>
  68. <script>
  69. var date = new Date();
  70. function calendar() {
  71. var year = date.getFullYear(),
  72. month = date.getMonth(),
  73. week = date.getDay(),
  74. day = date.getDate(),
  75. monthStr = ['一月', '二月', '三月', '四月', '五月', '六月', '七月', '八月', '九月', '十月', '十一月', '十二月'][month],
  76. weekDays = new Date(year, month, 1).getDay(),
  77. days = new Date(year, month + 1, 0).getDate();
  78. // 插入年
  79. document.getElementsByClassName('year')[0].innerHTML = year;
  80. // 插入月
  81. document.getElementsByClassName('month')[0].innerHTML = monthStr;
  82. // 插入日
  83. var dateStr = '', style;
  84. for (var i = 0; i < weekDays; i++) dateStr += `<li></li>`;
  85. for (var i = 1; i <= days; i++) {
  86. style = '';
  87. if (i === new Date().getDate() && year === new Date().getFullYear() && month === new Date().getMonth()) {
  88. style = ' class="active"';
  89. }
  90. dateStr += `<li${style}>${i}</li>`;
  91. }
  92. document.getElementsByClassName('date')[0].innerHTML = dateStr;
  93. }
  94. window.onload = calendar;
  95. document.getElementsByClassName('prev')[0].onclick = function () {
  96. date.setMonth(date.getMonth() - 1);
  97. calendar();
  98. }
  99. document.getElementsByClassName('next')[0].onclick = function () {
  100. date.setMonth(date.getMonth() + 1);
  101. calendar();
  102. }
  103. </script>
  104. </body>
  105. </html>

简易 javascript 日历

上一篇:

下一篇: