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

运行测试截图

相关推荐
张较瘦_19 小时前
[论文阅读] 软件工程 | 告别“线程安全玄学”:基于JMM的Java类静态分析,CodeQL3分钟扫遍GitHub千仓错误
java·论文阅读·安全
A尘埃21 小时前
智慧零售全渠道业务中台系统
java·零售
qczg_wxg1 天前
React Native的动画系统
javascript·react native·react.js
漂流瓶jz1 天前
解锁Babel核心功能:从转义语法到插件开发
前端·javascript·typescript
小wanga1 天前
C++知识
java·开发语言·c++
大怪v1 天前
老乡,别走!Javascript隐藏功能你知道吗?
前端·javascript·代码规范
我是渣哥1 天前
Java String vs StringBuilder vs StringBuffer:一个性能优化的探险故事
java·开发语言·jvm·后端·算法·职场和发展·性能优化
工一木子1 天前
深入Java并发:锁机制原理剖析与性能优化实战
java·性能优化·并发·
你我约定有三1 天前
java--写在 try 中的创建连接
java·开发语言