element-ui 中el-calendar 日历插件获取显示的第一天和最后一天【原创】

需要获取el-calendar 日历组件上的第1天和最后一天。可以通过document.querySelector()方法进行获取dom元素中的值,这样避免计算问题。

获取的过程中主要有两个难点,第1个是处理上1月和下1月的数据,第2个是跨年的数据。

直接贴代码,这个方法可以运用到1、点击上个月,今天、下个月三个按钮,实现点击获取最新的日历组件上的第1天和最后一天。2、通过watch实时监听。

javascript 复制代码
    getRange(date) {
      const today = date ? new Date(date) : new Date();

      // 初始化 startDate 和 endDate
      let startDate = null;
      let endDate = null;

      // 获取日历中的第一个和最后一个单元格
      let firstCell = document.querySelector('#pane-3 > div > div > div.el-calendar__body > table > tbody > tr:nth-child(1) > td:nth-child(1) > div > div > div:nth-child(1) > div > div');
      let lastCell = document.querySelector('#pane-3 > div > div > div.el-calendar__body > table > tbody > tr:nth-child(6) > td:nth-child(7) > div > div > div:nth-child(1) > div > div');

      // 设置 startDate
      if (firstCell && parseInt(firstCell.textContent.trim(), 10) > 1) {
        // 获取前一个月和年份
        let prevMonth = today.getMonth() - 1;
        let year = today.getFullYear();
        if (prevMonth < 0) {
          prevMonth = 11; // 上一年的12月
          year -= 1;
        }
        const monthStr = String(prevMonth + 1).padStart(2, '0'); // 月份从1开始
        const dayStr = String(firstCell.textContent.trim()).padStart(2, '0');
        startDate = `${year}-${monthStr}-${dayStr}`;
      } else {
        // 当月第一天
        const month = today.getMonth() + 1;
        const monthStr = String(month).padStart(2, '0');
        startDate = `${today.getFullYear()}-${monthStr}-01`;
      }

      // 设置 endDate
      if (lastCell && parseInt(lastCell.textContent.trim(), 10) < 30) {
        // 获取下一个月和年份
        let nextMonth = today.getMonth() + 1;
        let year = today.getFullYear();
        if (nextMonth > 11) {
          nextMonth = 0; // 下一年的1月
          year += 1;
        }
        const monthStr = String(nextMonth + 1).padStart(2, '0'); // 月份从1开始
        const dayStr = String(lastCell.textContent.trim()).padStart(2, '0');
        endDate = `${year}-${monthStr}-${dayStr}`;
      } else {
        // 当月最后一天
        const lastDay = new Date(today.getFullYear(), today.getMonth() + 1, 0).getDate();
        const month = today.getMonth() + 1;
        const monthStr = String(month).padStart(2, '0');
        endDate = `${today.getFullYear()}-${monthStr}-${String(lastDay).padStart(2, '0')}`;
      }

      // 返回包含 startDate 和 endDate 的对象
      return {
        startDate,
        endDate
      };
    }

运行测试截图

相关推荐
消失的旧时光-194318 分钟前
第四篇(实战): 订单表索引设计实战:从慢 SQL 到毫秒级
java·数据库·sql
それども39 分钟前
@ModelAttribute vs @RequestBody
java
利刃大大1 小时前
【Vue】Vue2 和 Vue3 的区别
前端·javascript·vue.js
雨中飘荡的记忆1 小时前
深度详解Spring Context
java·spring
Tao____1 小时前
JAVA开源物联网平台
java·物联网·mqtt·开源·ruoyi
Lhuu(重开版1 小时前
JS:正则表达式和作用域
开发语言·javascript·正则表达式
yqd6662 小时前
SpringSecurity的使用
java·spring
仙俊红2 小时前
Java Map 家族核心解析
java·开发语言
一嘴一个橘子2 小时前
springMvc 接收参数、cookie、header
java
code_li3 小时前
聊聊支付宝架构
java·开发语言·架构