html5 日历网页代码

这段代码创建了一个基本的HTML5日历,以表格形式呈现。你可以将其复制粘贴到一个HTML文件中并在浏览器中打开以查看效果。以下是一个简单的HTML5日历网页代码示例,它展示了一个基本的月份视图:

代码

<!DOCTYPE html>
<html lang=“en”>
<head>

<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Calendar</title>
<style>
    table {
        width: 100%;
        border-collapse: collapse;
    }
    th, td {
        padding: 10px;
        text-align: center;
        border: 1px solid #ccc;
    }
    th {
        background-color: #f2f2f2;
    }
</style>

</head> <body>

<h2>Calendar</h2>

<table>

<thead>
    <tr>
        <th>Sun</th>
        <th>Mon</th>
        <th>Tue</th>
        <th>Wed</th>
        <th>Thu</th>
        <th>Fri</th>
        <th>Sat</th>
    </tr>
</thead>
<tbody id="calendar-body">
</tbody>

</table>

<script>

function generateCalendar(year, month) {
    const calendarBody = document.getElementById("calendar-body");
    calendarBody.innerHTML = "";

    const firstDay = new Date(year, month, 1);
    const lastDay = new Date(year, month + 1, 0);
    const daysInMonth = lastDay.getDate();
    const startingDay = firstDay.getDay();

    let date = 1;
    for (let i = 0; i < 6; i++) {
        const row = document.createElement("tr");

        for (let j = 0; j < 7; j++) {
            if (i === 0 && j < startingDay) {
                const cell = document.createElement("td");
                row.appendChild(cell);
            } else if (date > daysInMonth) {
                break;
            } else {
                const cell = document.createElement("td");
                cell.textContent = date;
                row.appendChild(cell);
                date++;
            }
        }

        calendarBody.appendChild(row);
        if (date > daysInMonth) break;
    }
}

// Usage
const today = new Date();
const currentYear = today.getFullYear();
const currentMonth = today.getMonth();
generateCalendar(currentYear, currentMonth);

</script>

</body> </html>

过期时间:永久公开
创建于:2024-03-21 17:50
238