介绍
项目需要一个日历组件,在网上看了很多现成的,但没找到符合要求的,索性就自己实现吧。
先看效果图如下:
功能介绍:
1. 可以点击选择前后的月份;
2. 本月日期是黑字,其它月份日期是灰字;
3. 默认当天和选中日期是红圆底和白字;
4. 日期下面有红点,代表这天有回款金额(类似行程功能);
5. 点击事件日期,获取回款金额。
实现步骤
一、先实现基本的日历功能。
(1) 月份选择部分
箭头js代码
preMonth(){
if(this.currentMonth<1){
this.currentMonth = 11
this.currentYear--
}else{
this.currentMonth--;
}
}
nestMonth(){
if(this.currentMonth > 10){
this.currentMonth = 0
this.currentYear++
}else{
this.currentMonth++
}
}
箭头css代码
#preMouth{
display: inline-block;
border: .16rem solid #000;
border-top: .16rem solid transparent;
border-bottom: .16rem solid transparent;
border-left: .16rem solid transparent;
margin-right: .18rem;
}
#nextMouth{
display: inline-block;
border: .16rem solid #000;
border-top: .16rem solid transparent;
border-bottom: .16rem solid transparent;
border-right: .16rem solid transparent;
margin-left: .18rem;
}
(2) 日期部分
采用table实现。表头的星期固定。
weeks:['日','一','二','三','四','五','六']
-
行数:(当前月天数+当前月第一天星期数)/7取最小整数
- 当前月天数:
dayMouth:[31,28+this.isLeap(this.currentYear),31,30,31,30,31,31,30,31,30,31]- isLeap(year)计算是否闰年: year%100==0?((year%400==0)?1:0):(year%4==0?1:0)
- 当前月第一天星期数 new Date(this.currentYear,this.currentMonth,1).getDay()
- 当前月天数:
-
表格数量 = 行数*7
-
表格自然内容 = (行数-1)*7+一行第几格
- 设置表格自定义属性 day= 表格自然内容 (后面的点击事件会用)
- 设置表格自定义属性 day= 表格自然内容 (后面的点击事件会用)
-
表格日期内容 = 表格自然内容-当前月第一天星期数
-
调整表格日期内容:new Date(this.currentYear,this.currentMonth,表格自然内容).getDate()
- 如果 表格自然内容<0 || 表格自然内容>=当前月天数 字体变色
- 根据属性day判断是否当天日期或有数据的日期(后台获取),加class
二、点击事件
在表格上增加点击事件
clickDate(el){
this.currentClickDate = el
if(el.target.className.match(/hasInfo/)){//是否是数据的日期
let clickDate = new Date(this.currentYear,this.currentMouth,el.target.attributes.days.nodeValue).getTime();//获取时间
for(let i=0;i<this.days.length;i++){//遍历后台获取的有数据的日期数组
if(this.days[i] == clickDate){
this.$emit('money',this.item.date[i])
clickDate = null//清空
}
}
}else{
this.$emit('money','')
}
this.nowEL[0].className = this.nowEL[0].className.replace(/now/,' ')//移除之前当天日期CSS
el.target.className +=" now"//添加选中日期的CSS
}
结束!