当前位置:首页 > JavaScript

js实现日历方法

2026-04-07 16:49:44JavaScript

原生JavaScript实现日历

创建日历需要处理日期计算、月份切换以及界面渲染。以下是一个基础实现方案:

// 获取DOM元素
const calendar = document.getElementById('calendar');
const monthYearDisplay = document.getElementById('month-year');
const prevBtn = document.getElementById('prev');
const nextBtn = document.getElementById('next');

let currentDate = new Date();

// 初始化日历
function initCalendar() {
    updateCalendar();
    prevBtn.addEventListener('click', () => {
        currentDate.setMonth(currentDate.getMonth() - 1);
        updateCalendar();
    });
    nextBtn.addEventListener('click', () => {
        currentDate.setMonth(currentDate.getMonth() + 1);
        updateCalendar();
    });
}

// 更新日历显示
function updateCalendar() {
    monthYearDisplay.textContent = `${currentDate.toLocaleString('default', { month: 'long' })} ${currentDate.getFullYear()}`;

    const firstDay = new Date(currentDate.getFullYear(), currentDate.getMonth(), 1);
    const lastDay = new Date(currentDate.getFullYear(), currentDate.getMonth() + 1, 0);

    const daysInMonth = lastDay.getDate();
    const startingDay = firstDay.getDay();

    let html = '';

    // 添加空白单元格
    for (let i = 0; i < startingDay; i++) {
        html += `<div class="day empty"></div>`;
    }

    // 添加日期单元格
    for (let i = 1; i <= daysInMonth; i++) {
        html += `<div class="day">${i}</div>`;
    }

    calendar.innerHTML = html;
}

initCalendar();

使用第三方库实现日历

对于更复杂的日历需求,可以考虑使用成熟的库如FullCalendar:

js实现日历方法

// 安装FullCalendar
// npm install @fullcalendar/core @fullcalendar/daygrid

import { Calendar } from '@fullcalendar/core';
import dayGridPlugin from '@fullcalendar/daygrid';

document.addEventListener('DOMContentLoaded', function() {
    const calendarEl = document.getElementById('calendar');

    const calendar = new Calendar(calendarEl, {
        plugins: [dayGridPlugin],
        initialView: 'dayGridMonth',
        headerToolbar: {
            left: 'prev,next today',
            center: 'title',
            right: 'dayGridMonth,dayGridWeek,dayGridDay'
        }
    });

    calendar.render();
});

日历功能扩展

实现日期选择功能:

// 在updateCalendar函数中添加事件监听
function updateCalendar() {
    // ...之前的代码...

    // 添加日期单元格时添加点击事件
    for (let i = 1; i <= daysInMonth; i++) {
        const date = new Date(currentDate.getFullYear(), currentDate.getMonth(), i);
        html += `<div class="day" data-date="${date.toISOString()}">${i}</div>`;
    }

    calendar.innerHTML = html;

    // 添加日期选择事件
    document.querySelectorAll('.day:not(.empty)').forEach(day => {
        day.addEventListener('click', () => {
            const selectedDate = new Date(day.dataset.date);
            console.log('Selected date:', selectedDate);
        });
    });
}

样式基础示例

#calendar {
    display: grid;
    grid-template-columns: repeat(7, 1fr);
    gap: 5px;
    max-width: 600px;
}

.day {
    padding: 10px;
    text-align: center;
    border: 1px solid #ddd;
    cursor: pointer;
}

.day.empty {
    background-color: #f5f5f5;
}

.day:hover {
    background-color: #e9e9e9;
}

.header {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
}

注意事项

日期处理使用JavaScript的Date对象时要注意月份是从0开始的(0表示一月)

js实现日历方法

国际化显示可以使用toLocaleString方法设置不同语言环境

性能优化对于大量日期的渲染可以考虑虚拟滚动技术

移动端适配需要添加触摸事件支持并调整布局

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

相关文章

css制作日历

css制作日历

使用CSS Grid布局制作日历 日历的布局适合使用CSS Grid实现,因其天然的行列结构。以下是一个基础日历的HTML和CSS代码: <div class="calendar">…

vue commit 方法实现

vue commit 方法实现

Vue 中 Commit 方法的实现 在 Vue 中,commit 方法是 Vuex 的核心功能之一,用于提交 mutation 来修改状态。以下是实现 commit 方法的关键步骤: 初始化 St…

vue实现方法调用

vue实现方法调用

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

vue watch 实现方法

vue watch 实现方法

监听基本数据类型 在Vue中使用watch监听基本数据类型(如String、Number、Boolean)时,可以直接在watch选项中定义: data() { return { mes…

用vue实现日历

用vue实现日历

实现基础日历结构 使用Vue构建日历需要先设计基础数据结构。通常需要维护当前年份、月份以及日期数组。可以通过Date对象获取当前月份的天数和起始星期。 data() { return {…

vue实现多个方法异步

vue实现多个方法异步

Vue 中实现多个方法异步执行 在 Vue 中实现多个方法异步执行,可以通过多种方式实现,例如使用 Promise、async/await 或 Promise.all 来处理多个异步任务的并发或顺序执…