当前位置:首页 > JavaScript

js日历案例实现

2026-02-02 20:42:00JavaScript

实现基础日历功能

日历功能可以通过JavaScript结合HTML和CSS实现,核心是动态生成日期表格。以下代码展示了一个基础的日历生成器:

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

  let calendarHTML = '<table><tr><th>日</th><th>一</th><th>二</th><th>三</th><th>四</th><th>五</th><th>六</th></tr><tr>';

  // 填充月初空白
  for (let i = 0; i < firstDay.getDay(); i++) {
    calendarHTML += '<td></td>';
  }

  // 填充日期
  for (let day = 1; day <= daysInMonth; day++) {
    calendarHTML += `<td>${day}</td>`;
    if ((day + firstDay.getDay()) % 7 === 0) {
      calendarHTML += '</tr><tr>';
    }
  }

  calendarHTML += '</tr></table>';
  document.getElementById('calendar').innerHTML = calendarHTML;
}

// 使用当前年月初始化日历
const currentDate = new Date();
generateCalendar(currentDate.getFullYear(), currentDate.getMonth());

添加月份切换功能

扩展基础日历,增加月份导航控制:

js日历案例实现

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

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

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();
});

updateCalendar();

实现日期选择交互

为日历添加点击日期选择功能:

js日历案例实现

function generateCalendar(year, month) {
  // ...之前的基础日历代码...

  // 修改日期单元格生成部分
  for (let day = 1; day <= daysInMonth; day++) {
    const date = new Date(year, month, day);
    const isToday = date.toDateString() === new Date().toDateString();
    const cellClass = isToday ? 'today' : '';

    calendarHTML += `<td class="${cellClass}" data-date="${date.toISOString()}">${day}</td>`;
  }

  // ...之后的代码...
}

document.getElementById('calendar').addEventListener('click', (e) => {
  if (e.target.tagName === 'TD' && e.target.textContent) {
    const selectedDate = new Date(e.target.dataset.date);
    document.getElementById('selected-date').textContent = 
      `已选择: ${selectedDate.getFullYear()}-${selectedDate.getMonth()+1}-${selectedDate.getDate()}`;

    // 移除之前的选择样式
    document.querySelectorAll('#calendar td.selected').forEach(el => {
      el.classList.remove('selected');
    });

    // 添加新选择样式
    e.target.classList.add('selected');
  }
});

添加CSS样式增强视觉效果

基础样式使日历更美观:

table {
  border-collapse: collapse;
  width: 100%;
  max-width: 600px;
  margin: 0 auto;
}

th, td {
  border: 1px solid #ddd;
  padding: 8px;
  text-align: center;
}

th {
  background-color: #f2f2f2;
}

td:hover {
  background-color: #f5f5f5;
  cursor: pointer;
}

.today {
  background-color: #e6f7ff;
  font-weight: bold;
}

.selected {
  background-color: #1890ff;
  color: white;
}

.navigation {
  display: flex;
  justify-content: space-between;
  max-width: 600px;
  margin: 20px auto;
}

完整HTML结构示例

整合所有组件的完整HTML结构:

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <title>JavaScript日历</title>
  <style>
    /* 上述CSS样式 */
  </style>
</head>
<body>
  <div class="navigation">
    <button id="prev-month">上个月</button>
    <h2 id="month-display"></h2>
    <button id="next-month">下个月</button>
  </div>

  <div id="calendar"></div>
  <div id="selected-date" style="text-align: center; margin-top: 20px;"></div>

  <script>
    // 上述所有JavaScript代码
  </script>
</body>
</html>

这个实现包含了日历的核心功能:月份切换、日期选择、高亮显示今天日期。可以根据需要进一步扩展,如添加事件标记、多语言支持等功能。

标签: 日历案例
分享给朋友:

相关文章

vue实现全年日历功能

vue实现全年日历功能

实现全年日历功能 在Vue中实现全年日历功能,可以通过组合多个月份日历组件或使用第三方库来简化开发。以下是两种常见方法: 使用第三方库(如FullCalendar) 安装FullCalendar V…

react实现携程日历

react实现携程日历

实现携程日历的React组件 创建一个类似携程的日历组件需要处理日期选择、区间高亮、禁用日期等逻辑。以下是关键实现步骤: 日期选择与区间高亮 使用date-fns库处理日期操作,实现开始/结束日期选…

react实现日历

react实现日历

使用 React 实现日历 日历组件在 Web 应用中常用于日期选择、事件展示等场景。以下是几种实现日历的常见方法: 使用第三方库(如 react-calendar) 安装 react-calend…

react native实现案例

react native实现案例

React Native 实现案例 React Native 是一个流行的跨平台移动应用开发框架,允许开发者使用 JavaScript 和 React 构建高性能的 iOS 和 Android 应用。…

react 实现长列表案例

react 实现长列表案例

实现长列表的常用方法 虚拟滚动技术(Virtual Scrolling) 虚拟滚动通过仅渲染当前可视区域内的列表项来提升性能,适合超长列表场景。React生态中常用库如react-window或rea…

react实现日历翻页效果

react实现日历翻页效果

实现日历翻页效果的核心思路 日历翻页效果通常涉及日期数据的动态切换和动画过渡。React中可通过状态管理日期数据,结合CSS动画或第三方动画库实现视觉翻页效果。 基础实现步骤 状态管理 使用Reac…