前端实现一个日历表

1,028 阅读1分钟

1648614223(1).jpg

实现一个日历表,里面包括指定日历中的状态

调用如下:

let dataList = [new Date(),new Date(2022,0)]//定义需要展示的月份
dataList.map(item => {
  let data = calendarModule.getDateList(item)//这里是返回月份的日历,遍历这里面的数据展示在页面
})
// 生成日历模块
    const calendarModule = {
      getDateList: function(date=new Date()) {
        let year = date.getFullYear()
        let month = date.getMonth()
        let monthDays = new Array(31, 28 + this.leapYear(year), 31, 30, 31, 31, 30, 31, 30, 31, 30, 31)
        // 获取每个月的1日是星期几 
        let monthDayOne = new Date(2022,month,1)//todo
        let firstDay = monthDayOne.getDay()
        // 通过月总天数和该月第一天是星期几两个条件就可以得到行数
        let trNum = Math.ceil((monthDays[month]+firstDay)/7)
        let returnList = []
        //生成日历列表
        for(let arrIndex=0;arrIndex<trNum;arrIndex++) {
          returnList[arrIndex] = []
        }
        for(let i=0;i<trNum; i++) {
          for(let j=0;j<7;j++) {
            let idx = i*7+j//单元格自然序列号
            let dateNum = idx-firstDay+1//计算日期
            let click = 2
            if(dateNum>=21&&dateNum<=24) {
              click = 1
            }
            if(dateNum==20||dateNum==25) {
              click = 0
            }
            let obj = {
              value: dateNum>monthDays[month] ? 0:dateNum,//判断是否大于当月的总天数
              click
            }
            returnList[i][j] = obj
          }
        }
        return returnList
      },
      // 判断平年闰年2月份天数
      leapYear: function(year) {
        let res = 0
        year%100==0 ? res=(year%400==0?1:0) : res=(year%4==0?1:0)
        return res
      }
    }