DIV CSS 佈局教程網

用 jQuery 打造一個萬年曆
編輯:JavaScript綜合知識     

本文用 jQuery 實作一個萬年曆,可選擇年與月後動態產生該月的日曆,並滑過日期時有高亮效果、標記當天。

程式碼

<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 class='date1'>"+data[k]+"</div><br>");
    }else{
      $("#content").append("<div 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>

幾個關鍵技巧:days_in_month 用「下個月 0 號」的技巧算出當月天數;view 先算出該月第一天是星期幾(w)來決定前面留白格數,再逐格 append;年份下拉選單動態產生 1970–2998,並以 mouseover/mouseout 做日期高亮,最後把當天標成黃色。

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