当前位置:首页 > JavaScript

js实现日历方法

2026-02-02 23:00:33JavaScript

实现日历的基本思路

日历的核心功能包括显示当月日期、切换月份、高亮当前日期等。通过JavaScript动态生成HTML结构,结合CSS样式实现交互效果。

获取当前日期信息

使用Date对象获取当前年份、月份和日期,为后续生成日历提供基础数据。

const date = new Date();
let currentYear = date.getFullYear();
let currentMonth = date.getMonth();

生成月份日历

计算当月天数及首日星期,生成日期表格。需要考虑跨月日期的显示。

function generateCalendar(year, month) {
  const firstDay = new Date(year, month, 1).getDay();
  const daysInMonth = new Date(year, month + 1, 0).getDate();

  let dates = [];
  // 填充上月剩余日期
  for (let i = 0; i < firstDay; i++) {
    dates.push(null);
  }

  // 填充当月日期
  for (let i = 1; i <= daysInMonth; i++) {
    dates.push(i);
  }

  return dates;
}

渲染日历界面

将生成的日期数组转换为HTML元素,创建表格布局。

function renderCalendar(dates) {
  const calendarBody = document.getElementById('calendar-body');
  calendarBody.innerHTML = '';

  let row = document.createElement('tr');
  dates.forEach((date, index) => {
    if (index % 7 === 0 && index !== 0) {
      calendarBody.appendChild(row);
      row = document.createElement('tr');
    }

    const cell = document.createElement('td');
    cell.textContent = date || '';
    row.appendChild(cell);
  });

  calendarBody.appendChild(row);
}

添加月份切换功能

实现向前和向后翻页按钮,更新日历显示。

document.getElementById('prev-month').addEventListener('click', () => {
  currentMonth--;
  if (currentMonth < 0) {
    currentMonth = 11;
    currentYear--;
  }
  updateCalendar();
});

document.getElementById('next-month').addEventListener('click', () => {
  currentMonth++;
  if (currentMonth > 11) {
    currentMonth = 0;
    currentYear++;
  }
  updateCalendar();
});

function updateCalendar() {
  const dates = generateCalendar(currentYear, currentMonth);
  renderCalendar(dates);
  document.getElementById('month-year').textContent = 
    `${currentYear}年 ${currentMonth + 1}月`;
}

高亮当前日期

在日历中突出显示今天的日期,增强用户体验。

function highlightToday() {
  const today = new Date();
  if (today.getFullYear() === currentYear && today.getMonth() === currentMonth) {
    const cells = document.querySelectorAll('#calendar-body td');
    cells.forEach(cell => {
      if (parseInt(cell.textContent) === today.getDate()) {
        cell.classList.add('today');
      }
    });
  }
}

完整实现示例

结合HTML和CSS,以下是完整日历实现的核心代码:

<div class="calendar">
  <div class="header">
    <button id="prev-month">上个月</button>
    <h2 id="month-year"></h2>
    <button id="next-month">下个月</button>
  </div>
  <table>
    <thead>
      <tr>
        <th>日</th><th>一</th><th>二</th><th>三</th><th>四</th><th>五</th><th>六</th>
      </tr>
    </thead>
    <tbody id="calendar-body"></tbody>
  </table>
</div>
// 初始化日历
document.addEventListener('DOMContentLoaded', () => {
  updateCalendar();
  highlightToday();
});

日期选择功能扩展

为日历添加点击选择日期的交互功能,记录用户选择的日期。

document.getElementById('calendar-body').addEventListener('click', (e) => {
  if (e.target.tagName === 'TD' && e.target.textContent) {
    const selected = document.querySelector('.selected');
    if (selected) selected.classList.remove('selected');
    e.target.classList.add('selected');
    console.log(`选中日期: ${currentYear}-${currentMonth+1}-${e.target.textContent}`);
  }
});

响应式布局优化

通过CSS媒体查询确保日历在不同设备上都能正常显示。

@media (max-width: 600px) {
  .calendar {
    width: 100%;
  }
  td {
    padding: 5px;
    font-size: 14px;
  }
}

js实现日历方法

标签: 日历方法
分享给朋友:

相关文章

vue VUE实现日历组件功能

vue VUE实现日历组件功能

Vue 日历组件实现方法 基础日历结构 使用Vue的模板语法构建日历的HTML结构,通常包含头部(年月显示、切换按钮)和日历表格(星期标题和日期格子)。 <template> <…

vue怎么实现日历

vue怎么实现日历

实现基础日历布局 使用Vue的模板语法构建日历的HTML结构,通常采用表格形式展示日期。月份切换通过计算属性动态生成日期数组。 <template> <div class=…

Vue组件实现方法

Vue组件实现方法

Vue组件的基本实现 Vue组件是Vue.js的核心概念之一,允许将UI拆分为独立可复用的代码片段。组件的实现方式有多种,以下是常见的几种方法。 单文件组件(SFC) 单文件组件以.vue为后缀,…

js 实现日历

js 实现日历

实现日历的基本思路 日历的核心功能是展示日期,并允许用户进行日期选择或导航。JavaScript 可以动态生成日历的 HTML 结构,并处理用户交互逻辑。 基础日历结构 日历通常包含头部(显示月份和…

vue实现方法调用

vue实现方法调用

Vue 方法调用的实现方式 在 Vue 中,方法调用主要通过 methods 选项定义,并通过模板或脚本直接调用。以下是常见的实现方式: 在模板中直接调用方法 通过 v-on 指令(或简写 @)绑定…

vue登录实现方法

vue登录实现方法

实现登录功能的核心步骤 前端部分(Vue.js) 使用Vue CLI创建项目并安装必要依赖(axios、vue-router等)。创建登录组件包含表单,绑定v-model到data属性如usern…