JS实现简单日历
Posted Facker
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了JS实现简单日历相关的知识,希望对你有一定的参考价值。
/* //api num : year num : month num : date num : day num : time data: getData() data: preMonth() data: nextMonth() data: preYear() data: nextYear() data: thisMonth() data: costomDate() data{isToday,isThisMonth,date} */ function Calendar(studyWeek){ var calendar = new Object(); //日期数据基础 calendar.baseDate = new Date(); //初始化 calendar.init = function (){ this.year = this.baseDate.getFullYear(); this.month = this.baseDate.getMonth(); this.date = this.baseDate.getDate(); this.day = this.baseDate.getDay(); this.time = this.baseDate.getTime(); } calendar.init(); //获取数据 calendar.getData = function (){ var data = []; //起始值 var date = new Date(this.year,this.month,1); date.setTime(date.getTime() - 86400000 * date.getDay()); do{ for(var i=0; i<7; i++){ var obj = {}; obj.isThisMonth = date.getMonth() == this.month? true : false; obj.isToday = date.getDate() == this.date && date.getMonth() == new Date().getMonth() ? true : false; obj.isWeek = i == 0 || i == 6? true : false; obj.date = date.getDate(); obj.month = date.getMonth() + 1; obj.year = date.getFullYear(); obj.weekNum = this.setWeekNum(obj); data.push(obj); date.setTime(date.getTime() + 86400000); } } while(date.getMonth() == this.month); return data; } //设置周次 calendar.setWeekNum = function(obj){ var study = new Date(studyWeek.year, studyWeek.month, studyWeek.date).getTime(); var now = new Date(obj.year, obj.month, obj.date).getTime(); var weekNum = Math.ceil( (now - study) / (1000 * 60 * 60 * 24) / 7 ); return weekNum + 1; } //上月 calendar.preMonth = function (){ this.month--; this.baseDate.setMonth(this.month); this.init(); return this.getData(); } //下月 calendar.nextMonth = function (){ this.month++; this.baseDate.setMonth(this.month); this.init(); return this.getData(); } //上一年 calendar.preYear = function (){ this.year -= 1; this.baseDate.setFullYear(this.year); this.init(); return this.getData(); } //下一年 calendar.nextYear = function (){ this.year += 1; this.baseDate.setFullYear(this.year); this.init(); return this.getData(); } //本月 calendar.thisMonth = function (){ this.baseDate = new Date(); this.init(); return this.getData(); } //自定义年月 calendar.customDate = function (year,month){ this.year = +year; this.month = +month; this.baseDate.setFullYear(this.year); this.baseDate.setMonth(this.month - 1); this.init(); return this.getData(); } //返回值 return calendar; }
使用:
var calendar = new Calendar(); var data = calendar.getData();
根据获取的data进行自由渲染。
以上是关于JS实现简单日历的主要内容,如果未能解决你的问题,请参考以下文章