我想使用我自己設計的java腳本創建日期選擇器的日曆,而不使用任何j-query庫。我發現了一個代碼,我創建了日曆,但我不想找到如何在日曆中顯示五個下一個和上一個月的按鈕,並且我想突出顯示當前日期。我還需要點擊日期才能執行某些操作。它是如何做到的?請幫幫我。使用javascript的自定義日曆
這是我的代碼
// these are labels for the days of the week
cal_days_labels = ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat'];
// these are human-readable month name labels, in order
cal_months_labels = ['January', 'February', 'March', 'April',
'May', 'June', 'July', 'August', 'September',
'October', 'November', 'December'];
// these are the days of the week for each month, in order
cal_days_in_month = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
// this is the current date
cal_current_date = new Date();
function Calendar(month, year) {
this.month = (isNaN(month) || month == null) ? cal_current_date.getMonth() : month;
this.year = (isNaN(year) || year == null) ? cal_current_date.getFullYear() : year;
this.html = '';
}
Calendar.prototype.generateHTML = function() {
// get first day of month
var firstDay = new Date(this.year, this.month, 1);
var startingDay = firstDay.getDay();
// find number of days in month
var monthLength = cal_days_in_month[this.month];
// compensate for leap year
if (this.month == 1) { // February only!
if ((this.year % 4 == 0 && this.year % 100 != 0) || this.year % 400 == 0) {
monthLength = 29;
}
}
// do the header
var monthName = cal_months_labels[this.month]
var html = '<table class="calendar-table">';
html += '<tr><th colspan="7">';
html += monthName + " " + this.year;
html += '</th></tr>';
html += '<tr class="calendar-header">';
for (var i = 0; i <= 6; i++) {
html += '<td class="calendar-header-day">';
html += cal_days_labels[i];
html += '</td>';
}
html += '</tr><tr>';
// fill in the days
var day = 1;
// this loop is for is weeks (rows)
for (var i = 0; i < 9; i++) {
// this loop is for weekdays (cells)
for (var j = 0; j <= 6; j++) {
html += '<td class="calendar-day">';
if (day <= monthLength && (i > 0 || j >= startingDay)) {
html += day;
day++;
}
html += '</td>';
}
// stop making rows if we've run out of days
if (day > monthLength) {
break;
} else {
html += '</tr><tr>';
}
}
html += '</tr></table>';
this.html = html;
}
Calendar.prototype.getHTML = function() {
return this.html;
}
這是我的腳本來獲得日曆:
<script type="text/javascript">
var cal = new Calendar();
cal.generateHTML();
document.write(cal.getHTML());
</script>
事實證明,隨着時間,日期,時區工作,UTC抵消很多更復雜的比你想象的第一眼。特別是如果你開始把歷史上真正奇怪的東西包括在歷史上,哪些日子哪裏被統治者加入/刪除了掠奪者年代。爲了教育目的非常好,但如果你想創建一個產品,我會建議不要重新發明輪子和選擇一個庫(例如像momentjs; http://momentjs.com/) – 2015-04-03 07:55:00