想在自己的網頁裡放上一本隨時可查的萬年曆嗎?本文示範如何僅靠 jQuery 與原生 Date 物件,打造一個能自由切換年月的萬年曆,還能自動標出今天的日期,滑鼠移過日期格子時也有高亮回饋。
整個元件由三個關鍵函式支撐:getTime 負責把年月日轉成 Date 物件,days_in_month 用「下個月第 0 天」的技巧算出當月天數,而 view 則是重頭戲,負責計算第一天前面該留幾個空格、把日期填進七欄的格子裡,並綁定滑鼠移入移出的樣式切換。
<!Doctype html><html xmlns=https://www.w3.org/1999/xhtml>
<head>
<style>
.main{ width:600px; height:350px; background:gray; margin-left:auto; margin-right:auto; overflow:hidden; -webkit-border-radius:10px; -moz-border-radius:10px; }
.title{ text-align:center; }
.date{ float:left; padding-left:31px; }
.date1{ float:left; width:20px; height:20px; padding-top:10px; padding-left:30px; padding-right:30px; }
.content{ margin-left:25px; }
</style>
<script type="text/javascript" src="jquery.min.js"></script>
<script>
function getTime(year,month,day){
var myDate = new Date(year,month-1,day);
return myDate;
}
function days_in_month(year, month) {
return 32 - new Date(year, month - 1, 32).getDate();
}
function view(year,month){
var w = getTime(year,month,1).getDay()-1;
var num = days_in_month(year,month);
var index = 1;
var data = new Array();
for(var d = 0; d < num+w; d++){
if(d<w){ data[d] = ''; }else{ data[d] = index; index++; }
}
$("#content").html('');
for(var k = 0; k < data.length; k++){
if(k%7==0){ $("#content").append("<div id='t"+k+"' class='date1'>"+data[k]+"</div><br>"); }
else{ $("#content").append("<div id='t"+k+"' class='date1'>"+data[k]+"</div>"); }
}
$("#content > div").mouseover(function(){ if($(this).text()!=''){ $(this).css('background','red'); } });
$("#content > div").mouseout(function(){ if($(this).text()!=''){ $(this).css('background','gray'); } });
}
$(document).ready(function (){
for(var t = 1970; t < 2999; t++){ $("#yearsel").append("<option value ='"+t+"'>"+t+"</option>"); }
for(var y = 1; y < 13; y++){ $("#monthsel").append("<option value ='"+y+"'>"+y+"</option>"); }
var year = new Date().getFullYear();
var month = new Date().getMonth()+1;
var day = new Date().getDate();
var w = getTime(year,month,1).getDay()-1;
var num = day + w - 1;
$("#yearsel").change(function(){ year = $("#yearsel option:selected").text(); month = $("#monthsel option:selected").text(); view(year,month); });
$("#monthsel").change(function(){ year = $("#yearsel option:selected").text(); month = $("#monthsel option:selected").text(); view(year,month); });
var oDate = ['星期一','星期二','星期三','星期四','星期五','星期六','星期日'];
for(var i = 0; i < 7; i++){ $("#title").append("<div class='date'><b>"+oDate[i]+"</b></div>"); }
$("#yearsel option[value='"+year+"']").attr("selected", true);
view(year,month);
$("#t"+num).css('background','yellow');
});
</script>
</head>
<body>
<div id="main" class="main">
<center><h3>萬年歷</h3></center>
<select id="yearsel"></select>年
<select id="monthsel"></select>月<br><br>
<div id="title" class="title"></div>
<div id="content" class="content"></div>
</div>
</body>
</html>
小提醒:這份範例的星期對齊以「週日為第一天」為基準再減一,若你的顯示有偏移,只要微調 getDay() 的偏移量即可對齊你要的排版。