DIV CSS 佈局教程網

自己動手寫一個 JavaScript 日曆物件
編輯:關於JavaScript     

事情是這樣的:本來想直接從網路上找現成的日曆程式碼,結果發現不是太複雜難以修改,就是不好控制,不然就是相容性有問題。

想清楚之後發現,別人覺得很棒的不等於最適合自己。於是決定自己寫一個。

日曆主程式

var calendar={
STR:function(){with(this.data)return ""+Y+"年,"+M+"月,"+D+"號,星期"+WN[W];},
V:function(o,spli,sx){with(this)return o[sx]=""+data.Y+spli+data.M+spli+data.D},
T:function(){with(this)return data.TABLE},
dnY:function(){with(this){calendarChange(data.Y+1,data.M-1,data.D)}},
dnM:function(){with(this){calendarChange(data.Y,data.M,data.D)}},
upY:function(){with(this){calendarChange(data.Y-1,data.M-1,data.D)}},
upM:function(){with(this){calendarChange(data.Y,data.M-2,data.D)}},
day:function(o){with(this){data.D=o;calendarChange(data.Y,data.M-1,data.D)}},
data:{Y:null,M:null,D:null,W:null,H:null,U:null,YMD:null,YMD_C:"hot",ARR:null,TABLE:null,MN:null,WN:null,SELECT:null,TADAY:new Date(),TADAY_C:"taday",ROWLEN:7,VALUE:null},
creatTable:function(){with(this){
var table="<table height=100% width=100%><tr>"
for(var i=0;i<data.ROWLEN;i++){var t=data.WN[i]||"&nbsp;";table+="<th>"+t+"</th>";}
for(var i in data.ARR){var showText=data.ARR[i]||"&nbsp;",br=i%data.ROWLEN,title,css;
if(!br){table+="</tr><tr>"};
data.ARR[i]?title=data.Y+"-"+data.M+"-"+showText:title="";
String(data.TADAY.getDate())==String(data.ARR[i])?
(data.YMD.getFullYear()==data.TADAY.getFullYear()&&data.YMD.getMonth()==data.TADAY.getMonth()&&data.YMD.getDate()==data.TADAY.getDate())?
css=data.TADAY_C+" "+data.YMD_C:css=data.YMD_C:css="";
table+="<td title='"+title+"' class="+css+">"+showText+"</td>";
}table+="</tr></table>"
data.TABLE=table;return table;
}},
calendarStarArr:function(userY,userM,userD){with(this){
var Arr=[];
var now = new Date(userY,userM,userD);
var LastDay = now.getLastDay();
var FirstDayofWeek = now.FirstDayofWeek();
data.YMD=now;data.Y=now.getFullYear();
data.M=now.getMonth()+1;data.D=now.getDate();data.W=now.getDay();
while(Arr.length!=FirstDayofWeek){Arr.push(false)}
for(var i=0;i<LastDay;i++){Arr.push(i+1)}
while(Arr.length%data.ROWLEN!=0){Arr.push(false)}
data.ARR=Arr;return Arr;
}},
calendarChange:function(userY,userM,userD){with(this){
calendarStarArr(userY,userM,userD);creatTable()
}},
calendarStar:function(userY,userM,userD){with(this){
data.MN = ["零","一","二","三","四","五","六","七","八","九","十","十一","十二"];
data.WN = ["日","一","二","三","四","五","六"];
calendarChange(userY,userM,userD);
}},
init:function(){with(this){
Date.prototype.getLastDay=function(){return(new Date(this.getFullYear(),this.getMonth()+1,0).getDate())}
Date.prototype.FirstDayofWeek=function(){return(new Date(this.getFullYear(),this.getMonth(),1).getDay())}
calendarStar(new Date().getFullYear(),new Date().getMonth(),new Date().getDate())
}}
}

API 說明

var aa=new calendar()  // 建立一個日曆物件
aa.init()              // 初始化
obj.innerHTML=aa.STR()  // 顯示日期字串
obj.innerHTML=aa.T()    // 顯示表格 HTML
aa.dnY()                // 下一年
aa.upY()                // 上一年
aa.dnM()                // 下一月
aa.upM()                // 上一月
aa.day(Number)          // 切換到指定日期,需傳入數值型參數

這個物件只負責日曆的核心邏輯:日期計算、月份排列、表格 HTML 產生。至於日曆要放在哪裡、哪個事件觸發哪個方法,刻意留給呼叫方決定——否則就失去了自己動手寫的意義。

完整可運行的範例

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>js日歷效果-wangzf</title>
</head>
<style>
html,body{height:100%;width:100%;}
*{margin:0;padding:0;}
.calendarBox{width:100%;}
#calendar_control{background:#a3a3b4;}
#calendar_control input{min-width:inherit;}
#calendarBox{width:100%;height:100%;}
#calendar_str{cursor:pointer;text-align:center;font-weight:lighter;}
#calendar_body td{background:#f0f0f0;cursor:pointer;}
#calendar_body td.taday{background:#0CF;}
#calendar_body td.hot{background:#FF6;}
#calendar_body th{background:#3f526f;color:#fff;}
#calendar_body td,#calendar_body th{text-align:center;}
</style>
<script>
var calendar={
STR:function(){with(this.data)return ""+Y+"年,"+M+"月,"+D+"號,星期"+WN[W];},
V:function(spli){with(this)return ""+data.Y+spli+data.M+spli+data.D},
T:function(){with(this)return data.TABLE},
dnY:function(){with(this){calendarChange(data.Y+1,data.M-1,data.D)}},
dnM:function(){with(this){calendarChange(data.Y,data.M,data.D)}},
upY:function(){with(this){calendarChange(data.Y-1,data.M-1,data.D)}},
upM:function(){with(this){calendarChange(data.Y,data.M-2,data.D)}},
day:function(o){with(this){data.D=o;calendarChange(data.Y,data.M-1,data.D)}},
data:{Y:null,M:null,D:null,W:null,H:null,U:null,YMD:null,YMD_C:"hot",ARR:null,TABLE:null,MN:null,WN:null,SELECT:null,TADAY:new Date(),TADAY_C:"taday",ROWLEN:7,VALUE:null},
creatTable:function(){with(this){
var table="<table height=100% width=100%><tr>"
for(var i=0;i<data.ROWLEN;i++){var t=data.WN[i]||" ";table+="<th>"+t+"</th>";}
for(var i in data.ARR){var showText=data.ARR[i]||" ",br=i%data.ROWLEN,title,css="";
if(!br){table+="</tr><tr>"};
data.ARR[i]?title=data.Y+"-"+data.M+"-"+showText:title="";
if(String(data.D)==String(data.ARR[i])){css+=" "+data.YMD_C;}
if(data.YMD.getFullYear()==data.TADAY.getFullYear()&&data.YMD.getMonth()==data.TADAY.getMonth()&&String(data.TADAY.getDate())==String(data.ARR[i])){css=" "+data.TADAY_C}
table+="<td title='"+title+"' class="+css+">"+showText+"</td>";
}table+="</tr></table>"
data.TABLE=table;return table;
}},
calendarStarArr:function(userY,userM,userD){with(this){
var Arr=[];
var now = new Date(userY,userM,userD);
var LastDay = now.getLastDay();
var FirstDayofWeek = now.FirstDayofWeek();
data.YMD=now;data.Y=now.getFullYear();
data.M=now.getMonth()+1;data.D=now.getDate();data.W=now.getDay();
while(Arr.length!=FirstDayofWeek){Arr.push(false)}
for(var i=0;i<LastDay;i++){Arr.push(i+1)}
while(Arr.length%data.ROWLEN!=0){Arr.push(false)}
data.ARR=Arr;return Arr;
}},
calendarChange:function(userY,userM,userD){with(this){
calendarStarArr(userY,userM,userD);creatTable()
}},
calendarStar:function(userY,userM,userD){with(this){
data.MN = ["零","一","二","三","四","五","六","七","八","九","十","十一","十二"];
data.WN = ["日","一","二","三","四","五","六"];
calendarChange(userY,userM,userD);
}},
init:function(){with(this){
Date.prototype.getLastDay=function(){return(new Date(this.getFullYear(),this.getMonth()+1,0).getDate())}
Date.prototype.FirstDayofWeek=function(){return(new Date(this.getFullYear(),this.getMonth(),1).getDay())}
calendarStar(new Date().getFullYear(),new Date().getMonth(),new Date().getDate())
}}
}
</script>
<body id="body">
<table width="100%" height="100%" border="0" cellspacing="0" cellpadding="0">
<tr height="10%">
<td><table width="100%" height="100%" border="0" cellspacing="0" cellpadding="0" id="calendar_control">
<tr>
<th width="20%" align="left" scope="col">
<input type="button" title="上一年" value="<<" id="calendar_upY" />
<input type="button" title="上一月" value="<" id="calendar_upM" /></th>
<th width="56%" id="calendar_str" scope="col" title="點擊返回今天."></th>
<th width="24%" align="right" scope="col">
<input type="button" title="下一年" value=">>" id="calendar_dnY" />
<input type="button" title="下一月" value=">" id="calendar_dnM" /></th>
</tr>
</table></td>
</tr>
<tr>
<td height="90%" id="calendar_body"></td>
</tr>
</table>
<script>
calendar.init()
function calendarChange(){
  var calendar_body=document.getElementById("calendar_body")
  calendar_body.innerHTML=calendar.T()  // 顯示表格
  var calendar_str=document.getElementById("calendar_str")
  calendar_str.innerHTML=calendar.STR()  // 顯示日期字串
  calendarControl()                     // 呼叫日曆控制
}
calendarChange()                          // 日曆更新
function calendarControl(){
  var calendar_str=document.getElementById("calendar_str")
  calendar_str.onclick=function(){ calendar.init();calendarChange()}  // 返回今天
  var calendar_dnY=document.getElementById("calendar_dnY")
  calendar_dnY.onclick=function(){ calendar.dnY();calendarChange()}  // 下一年
  var calendar_dnM=document.getElementById("calendar_dnM")
  calendar_dnM.onclick=function(){ calendar.dnM();calendarChange()}  // 下一月
  var calendar_upY=document.getElementById("calendar_upY")
  calendar_upY.onclick=function(){ calendar.upY();calendarChange()}  // 上一年
  var calendar_upM=document.getElementById("calendar_upM")
  calendar_upM.onclick=function(){ calendar.upM();calendarChange()}  // 上一月
  var calendar_day=document.getElementById("calendar_body").getElementsByTagName("td");
  for(var i in calendar_day){
    calendar_day[i].onclick=function(){
      var N=Number(this.innerText);
      if(N){calendar.day(N);calendarChange()}
    }
  }  // 當天日期
}
</script>
</body>
</html>

設計上的取捨

幾個值得說清楚的決定:

  • 表格用字串拼接:直接產生 HTML 字串再由 innerHTML 塞入,比反覆 createElement / appendChild 更省事,程式碼也更好讀。
  • 兩個 Date 原型擴充:getLastDay() 取當月天數,FirstDayofWeek() 取該月首日是星期幾,用來決定前面要補幾個空格子。
  • 狀態集中管理:所有狀態放在 data 物件裡,包含當年當月當日、表格快取、星期的中文對照表等,避免變數散落。
  • 今天與選中日的樣式分離:透過 TADAY_C 與 YMD_C 兩個 class 名稱區分,樣式完全交給 CSS 決定。

最後要誠實提醒:這份程式碼大量使用了 with 語句,在現代 JavaScript(ES5 嚴格模式與後續標準)中已被禁用,因此不建議直接搬到新專案。它的價值在於示範「把日曆邏輯抽象成一個物件、狀態與渲染分離」的思路——換成 ES6 class 或模組化寫法,同樣的結構依然成立。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved