JavaScri…">
当前位置:首页 > JavaScript

js实现日期表格

2026-03-16 06:54:53JavaScript

实现日期表格的步骤

HTML结构
创建一个基本的HTML结构,包含一个表格元素用于显示日期。

js实现日期表格

<div id="calendar"></div>

JavaScript逻辑
使用JavaScript动态生成日期表格,通常包括以下功能:

js实现日期表格

  • 获取当前月份的天数
  • 确定月份的第一天是星期几
  • 生成表格的行和列
function generateCalendar(year, month) {
  const calendar = document.getElementById('calendar');
  const firstDay = new Date(year, month, 1);
  const lastDay = new Date(year, month + 1, 0);
  const daysInMonth = lastDay.getDate();
  const startingDay = firstDay.getDay(); // 0 (Sunday) to 6 (Saturday)

  let html = '<table>';
  html += '<tr><th>Sun</th><th>Mon</th><th>Tue</th><th>Wed</th><th>Thu</th><th>Fri</th><th>Sat</th></tr>';

  let date = 1;
  for (let i = 0; i < 6; i++) {
    if (date > daysInMonth) break;
    html += '<tr>';
    for (let j = 0; j < 7; j++) {
      if (i === 0 && j < startingDay) {
        html += '<td></td>';
      } else if (date > daysInMonth) {
        html += '<td></td>';
      } else {
        html += `<td>${date}</td>`;
        date++;
      }
    }
    html += '</tr>';
  }
  html += '</table>';
  calendar.innerHTML = html;
}

// 调用函数生成当前月份的日历
const currentDate = new Date();
generateCalendar(currentDate.getFullYear(), currentDate.getMonth());

样式调整
通过CSS美化日历表格,使其更易读。

table {
  border-collapse: collapse;
  width: 100%;
}
th, td {
  border: 1px solid #ddd;
  padding: 8px;
  text-align: center;
}
th {
  background-color: #f2f2f2;
}

功能扩展

  • 添加月份切换按钮
  • 高亮当前日期
  • 支持事件点击
// 示例:高亮当前日期
const currentDay = new Date().getDate();
const cells = document.querySelectorAll('td');
cells.forEach(cell => {
  if (cell.textContent == currentDay) {
    cell.style.backgroundColor = '#ffcccb';
  }
});

通过以上步骤,可以实现一个基本的日期表格,并支持进一步的功能扩展。

标签: 表格日期
分享给朋友:

相关文章

vue实现重置表格数据

vue实现重置表格数据

重置表格数据的方法 在Vue中重置表格数据通常涉及清空或重新初始化数据绑定的数组或对象。以下是几种常见实现方式: 直接重置数据源 对于基于数组的表格数据,可以直接将数据数组重置为空或初始值:…

vue实现动态用户表格

vue实现动态用户表格

Vue 动态用户表格实现方法 基础表格结构 使用<table>或第三方组件库(如Element UI的el-table)构建基础框架。静态数据示例: <template>…

css表格制作表格

css表格制作表格

CSS 表格制作方法 基础表格结构 使用HTML的<table>标签创建表格框架,搭配<tr>(行)、<td>(单元格)和<th>(表头)标签: &l…

vue实现表格输入

vue实现表格输入

Vue实现表格输入的方法 基础表格实现 使用v-for指令动态渲染表格行和列,结合v-model实现双向数据绑定。 <template> <table> <…

vue实现表格滑动

vue实现表格滑动

Vue实现表格滑动的方法 使用CSS overflow属性实现横向滑动 在表格外层容器设置overflow-x: auto,限制表格宽度超出时出现滚动条。这种方法适合简单场景,无需额外依赖库。 &l…

vue 实现页面 表格

vue 实现页面 表格

Vue 实现页面表格的方法 Vue 提供了多种方式实现表格功能,可以根据需求选择不同的方案。以下是常见的实现方法: 使用原生 HTML 表格 通过 Vue 的模板语法直接渲染表格数据: <t…