关于用JAVASCRIPT做日历的问题!

JavaScript09

关于用JAVASCRIPT做日历的问题!,第1张

<html>

<head><meta http-equiv="Content-Type" content="text/htmlcharset=gb2312">

<title>日期选择 - BY ziyue</title>

<script language="JavaScript" type="text/JavaScript">

/*=======Calendar.js=======By Jiang Hongbin=======*/

var months = new Array("一月", "二月", "三月", "四月", "五月", "六月", "七月", "八月", "九月", "十月", "十一月", "十二月")

var daysInMonth = new Array(31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31)

var days = new Array("日","一", "二", "三", "四", "五", "六")

var today

document.writeln("<div id='Calendar' style='position:absolutez-index:1visibility: hiddenfilter:\"progid:DXImageTransform.Microsoft.Shadow(direction=135,color=#999999,strength=3)\"'></div>")

function getDays(month, year)

{

//下面的这段代码是判断当前是否是闰年的

if (1 == month)

return ((0 == year % 4) &&(0 != (year % 100))) || (0 == year % 400) ? 29 : 28

else

return daysInMonth[month]

}

function getToday()

{

//得到今天的年,月,日

this.now = new Date()

this.year = this.now.getFullYear()

this.month = this.now.getMonth()

this.day = this.now.getDate()

}

function getStringDay(str)

{

//得到输入框的年,月,日

var str=str.split("-")

this.now = new Date(parseFloat(str[0]),parseFloat(str[1])-1,parseFloat(str[2]))

this.year = this.now.getFullYear()

this.month = this.now.getMonth()

this.day = this.now.getDate()

}

function newCalendar() {

var parseYear = parseInt(document.all.Year.options[document.all.Year.selectedIndex].value)

var newCal = new Date(parseYear, document.all.Month.selectedIndex, 1)

var day = -1

var startDay = newCal.getDay()

var daily = 0

if ((today.year == newCal.getFullYear()) &&(today.month == newCal.getMonth()))

day = today.day

var tableCal = document.all.calendar

var intDaysInMonth =getDays(newCal.getMonth(), newCal.getFullYear())

for (var intWeek = 1intWeek <tableCal.rows.lengthintWeek++)

for (var intDay = 0intDay <tableCal.rows[intWeek].cells.lengthintDay++)

{

var cell = tableCal.rows[intWeek].cells[intDay]

if ((intDay == startDay) &&(0 == daily))

daily = 1

if(day==daily) //今天,调用今天的Class

{

cell.style.background='#6699CC'

cell.style.color='#FFFFFF'

//cell.style.fontWeight='bold'

}

else if(intDay==6) //周六

cell.style.color='green'

else if (intDay==0) //周日

cell.style.color='red'

if ((daily >0) &&(daily <= intDaysInMonth))

{

cell.innerText = daily

daily++

}

else

cell.innerText = ""

}

}

function GetDate(InputBox)

{

var sDate

//这段代码处理鼠标点击的情况

if (event.srcElement.tagName == "TD")

if (event.srcElement.innerText != "")

{

sDate = document.all.Year.value + "-" + document.all.Month.value + "-" + event.srcElement.innerText

eval("document.all."+InputBox).value=sDate

HiddenCalendar()

}

}

function HiddenCalendar()

{

//关闭选择窗口

document.all.Calendar.style.visibility='hidden'

}

function ShowCalendar(InputBox)

{

var x,y,intLoop,intWeeks,intDays

var DivContent

var year,month,day

//var o=document.getElementById(InputBox)

var o=InputBox

var oid=o.id

var thisyear//真正的今年年份

if(!oid)oid=o.name

thisyear=new getToday()

thisyear=thisyear.year

today = o.value

if(isDate(today))

today = new getStringDay(today)

else

today = new getToday()

//显示的位置

x=o.offsetLeft

y=o.offsetTop

while(o=o.offsetParent)

{

x+=o.offsetLeft

y+=o.offsetTop

}

document.all.Calendar.style.left=x+2

document.all.Calendar.style.top=y+20

document.all.Calendar.style.visibility="visible"

//下面开始输出日历表格(border-color:#9DBAF7)

DivContent="<table border='0' cellspacing='0' style='border:1px solid #0066FFbackground-color:#EDF2FC'>"

DivContent+="<tr>"

DivContent+="<td style='border-bottom:1px solid #0066FFbackground-color:#C7D8FA'>"

//年

DivContent+="<select name='Year' id='Year' onChange='newCalendar()' style='font-family:Verdanafont-size:12px'>"

for (intLoop = thisyear - 100intLoop <(thisyear + 2)intLoop++)

DivContent+="<option value= " + intLoop + " " + (today.year == intLoop ? "Selected" : "") + ">" + intLoop + "</option>"

DivContent+="</select>"

//月

DivContent+="<select name='Month' id='Month' onChange='newCalendar()' style='font-family:Verdanafont-size:12px'>"

for (intLoop = 0intLoop <months.lengthintLoop++)

DivContent+="<option value= " + (intLoop + 1) + " " + (today.month == intLoop ? "Selected" : "") + ">" + months[intLoop] + "</option>"

DivContent+="</select>"

DivContent+="</td>"

DivContent+="<td style='border-bottom:1px solid #0066FFbackground-color:#C7D8FAfont-weight:boldfont-family:Wingdings 2,Wingdings,Webdingsfont-size:16pxpadding-top:2pxcolor:#4477FFcursor:hand' align='center' title='关闭' onClick='javascript:HiddenCalendar()'>S</td>"

DivContent+="</tr>"

DivContent+="<tr><td align='center' colspan='2'>"

DivContent+="<table id='calendar' border='0' width='100%'>"

//星期

DivContent+="<tr>"

for (intLoop = 0intLoop <days.lengthintLoop++)

DivContent+="<td align='center' style='font-size:12px'>" + days[intLoop] + "</td>"

DivContent+="</tr>"

//天

for (intWeeks = 0intWeeks <6intWeeks++)

{

DivContent+="<tr>"

for (intDays = 0intDays <days.lengthintDays++)

DivContent+="<td onClick='GetDate(\"" + oid + "\")' style='cursor:handborder-right:1px solid #BBBBBBborder-bottom:1px solid #BBBBBBcolor:#215DC6font-family:Verdanafont-size:12px' align='center'></td>"

DivContent+="</tr>"

}

DivContent+="</table></td></tr></table>"

document.all.Calendar.innerHTML=DivContent

newCalendar()

}

function isDate(dateStr)

{

var datePat = /^(\d{4})(\-)(\d{1,2})(\-)(\d{1,2})$/

var matchArray = dateStr.match(datePat)

if (matchArray == null) return false

var month = matchArray[3]

var day = matchArray[5]

var year = matchArray[1]

if (month <1 || month >12) return false

if (day <1 || day >31) return false

if ((month==4 || month==6 || month==9 || month==11) &&day==31) return false

if (month == 2)

{

var isleap = (year % 4 == 0 &&(year % 100 != 0 || year % 400 == 0))

if (day >29 || (day==29 &&!isleap)) return false

}

return true

}

</script>

<style type="text/css">

<!--

td,input {

font-family: Verdana, Arial, Helvetica, sans-serif

font-size: 12px

}

-->

</style>

</head>

<body>

<form name="form1" method="post" action="">

<table width="500" border="0" align="center" cellspacing="1" bgcolor="#CCCCCC">

<tr bgcolor="#FFFFFF">

<td align="right">您的生日:</td>

<td><input name="birthday" type="text" id="birthday" title="点击选择" onClick="javascript:ShowCalendar(this)" size="20">

<input type="button" name="Submit" value="选 择" onClick="javascript:ShowCalendar(form1.birthday)"></td>

<td>BLOG:<a href="http://web-v.com/">http://web-v.com/</a></td>

</tr>

</table>

</form>

</body>

</html>

首先必须解决的问题是表格的行与列问题。列是固定的,七列,因为一周有七天。行需要动态计算,因为,每一个月的第一天是星期几是一个变数,因而第一天在表格中的第几个单元也就跟着变化,同时,每个月的总天数不一致也影响着各个月对表格行数的需要量。

一. 表格的行数问题

1.首先取得处理月的总天数

JS不提供此参数,我们需要计算。考虑到闰年问题会影响二月份的天数,我们先编写一个判断闰年的自编函数:

function is_leap(year) {

return (year%100==0?res=(year%400==0?1:0):res=(year%4==0?1:0))

}

接着定义一个包含十二个月在内的月份总天数的数组:

m_days=new Array(31,28+is_leap(ynow),31,30,31,31,30,31,30,31,30,31)

m_days这个数组里,二月份的天数已经加入闰年的信息:28+is_leap(ynow)。数组元素从0开始,正好对应于JS提供的Date函数提供的getMonth返回值,即0表示一月,1表示二月,2表示三月,依此类推。

这样,各月总数可以这样取得:m_days[x]。其中,x为0至11的自然数。

2.计算处理月第一天是星期几

可以使用Date函数的getDay取得,返回的值从0到6,0表示星期一,1表示星期二,2表示星期三,其余依此类推。代码如下(假设要处理的时间为2008年3月):

n1str=new Date(2008,3,1)

firstday=n1str.getDay()

有了月总天数和该月第一天是星期几这两个已知条件,就可以解决表格所需行数问题:(当前月天数+第一天是星期几的数值)除以七。表格函数需要整数,因此,我们使用Math.ceil来处理:

tr_str=Math.ceil((m_days[mnow] + firstday)/7)

表格中的tr标签实际上代表表格的行,因此变量tr_str是我们往下写表格的重要依据。

二. 打印日历表格

可以使用两个for语句嵌套起来实现:外层for语句写行,内层for语句写单元格。

for(i=0i<tr_stri++) { //外层for语句 - tr标签

document.write("<tr>")

for(k=0k<7k++) { //内层for语句 - td标签

idx=i*7+k//表格单元的自然序号

date_str=idx-firstday+1//计算日期

//这里是处理有效日期代码

} //内层for语句结束

document.write("</tr>")

} //外层for语句结束

单元格的自然序号是否代表有效日期非常关键,为此必须加入一个过滤机制:仅打印有效的日期。有效的日期大于0小于小于等于处理月的总天数。