基于javascript实现日历功能原理及代码实例
var date = new Date();
var year = date.getFullYear();
var month=date.getMonth();
var day = date.getDate();
var week=date.getDay();
var p=(week-day+1+35)%7+day-1;
var monthName=[
"January","February","March","April","May","June","July","August","September","October","November","December"
];
var monthNum=[
31,28,31,30,31,30,31,31,30,31,30,31
];
var weekName=[
"Su","Mo","Tu","We","Th","Fr","Sa"
];
var aimmonth=month,aimyear=year;
function init(){
createTitle(year,month);
var weekdays=document.getElementById("weekdays");
for(var i=0;i<7;i++){
var x = document.createElement("LI");
var t = document.createTextNode(weekName[i]);
x.appendChild(t);
weekdays.appendChild(x);
}
delDay();
createDay();
isnow();
}
function change(x){
aimmonth+=x;
if(aimmonth==-1){
aimyear-=1;
aimmonth=11;
}else if(aimmonth==12){
aimyear+=1;
aimmonth=0;
}
createTitle(aimyear,aimmonth);
delDay();
createDay();
isnow();
}
function createTitle(y,m){
document.getElementById("year").innerHTML=y;
document.getElementById("month").innerHTML=monthName[m];
}
function createDay(){
var datetmp=new Date();
datetmp.setFullYear(aimyear,aimmonth,1);
var firstday=datetmp.getDay();
var days=document.getElementById("days");
for(var i=0;i var x = document.createElement("LI"); var t = document.createTextNode(""); x.appendChild(t); days.appendChild(x); } for(var i=1;i<=getMonthDay();i++){ var x = document.createElement("LI"); var t = document.createTextNode(i); x.appendChild(t); days.appendChild(x); } } function delDay(){ var list=document.getElementById("days"); var len=list.childNodes.length; for(var i=0;i list.removeChild(list.childNodes[0]); } } function isnow(){ if(aimyear==year&&aimmonth==month){ days.childNodes[p].style="padding: 5px;background: #1abc9c;color: white !important;" } } function getMonthDay(){ if(aimmonth!=2){ return monthNum[aimmonth]; }else{ if(aimyear%4!=0||aimyear%100==0&&aimyear%400!=0){ return monthNum[aimmonth]; } else return 29; } } //main init();