JavaScript实现简单的日历
程序员文章站
2023-12-21 18:34:29
...
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<title>Js日历</title>
<style type="text/css">
.evrday {
width: 14%;
float: left;
}
#calendar {
width: 400px;
margin: auto;
}
button {
width: 25%;
height: 40px;
float: left;
}
div {
margin-top: 10px;
margin-bottom: 5px;
text-align: center;
}
#month {
width: 50%;
float: left;
}
</style>
</head>
<body onLoad="showday()">
<div id="calendar">
<div>
<button onClick="shang()">上个月</button>
<div id="month"></div>
<button onClick="next()">下个月</button>
</div>
<div>
<div class="evrday">日</div>
<div class="evrday">一</div>
<div class="evrday">二</div>
<div class="evrday">三</div>
<div class="evrday">四</div>
<div class="evrday">五</div>
<div class="evrday">六</div>
</div>
<div id="day"></div>
</div>
<script>
var today = new Date();
var year = today.getFullYear();
var month = today.getMonth() + 1;
var day = today.getDate();
var allday = 0;
function showmonth() {
var year_month = year + "年" + month + "月" + day + "日";
document.getElementById("month").innerHTML = year_month;
}
function count() {
if (month != 2) {
if (month == 4 || month == 6 || month == 9 || month == 11)
allday = 30;
else
allday = 31;
} else {
if ((year % 4 == 0 && year % 100 != 0) || (year % 400 == 0))
allday = 29;
else
allday = 28;
}
}
function showday() {
showmonth()
count();
var fistdate = new Date(year, month - 1, 1);
var xinqi = fistdate.getDay();
var daterow = document.getElementById("day");
for (var i = 0; i < xinqi; i++)
{
var dayElement = document.createElement("div");
dayElement.className = "evrday";
daterow.appendChild(dayElement);
}
for (var j = 1; j <= allday; j++) {
var dayElement = document.createElement("div");
dayElement.innerHTML = j;
dayElement.className = "evrday";
if (j == day)
dayElement.style.color = "red";
daterow.appendChild(dayElement);
}
}
//下个月
function next() {
document.getElementById('day').innerHTML = "";
if (month < 12) {
month = month + 1;
} else {
month = 1;
year = year + 1;
}
document.getElementById('div').innerHTML = showday();
}
//上个月
function shang() {
document.getElementById('day').innerHTML = "";
if (month > 1) {
month = month - 1;
} else {
month = 12;
year = year - 1;
}
document.getElementById('div').innerHTML = showday();
}
</script>
</body>
</html>
效果图
就是不知道这个报错是怎么回事。。。
另外想实现回到今天的功能,想了一会,发现没思路。。。。试了几次都是BUG,就。。。就算了。。。