日历实现:
点左右的箭头可以跳到想看的月份日历。
index.html:
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>简单日历</title>
<link rel="stylesheet" href="css/rl.css"/>
<script src="js/rl.js"></script>
</head>
<body onload="showDate();">
<div>
<div id="calendar">
<div>
<button onclick="lastMonth();"><img src="img/left.png"/></button>
<span id="dqrq"></span>
<button onclick="nextMonth();"><img src="img/right.png"/></button>
</div>
<div>
<div class="everyday">日</div>
<div class="everyday">一</div>
<div class="everyday">二</div>
<div class="everyday">三</div>
<div class="everyday">四</div>
<div class="everyday">五</div>
<div class="everyday">六</div>
</div>
<div id="day"></div>
</div>
</div>
</body>
</html>
rl.css:
div{
text-align: center;
margin-top: 10px;
margin-bottom: 10px;
}
#calendar{
border-bottom: 1px black solid;
width:400px;
margin:auto;
}
button{
border:none;
background-color: white;
width:20px;
height: 20px;
}
#month{
width: 320px;
float:left;
height: 40px;
margin-top: 0;
margin-bottom: 0;
}
.everyday{
width:56px;
float: left;
}
rl.js:
var today=new Date();
var year=today.getFullYear();//获得年份
var month=today.getMonth()+1;//获得月份,getMonth是从0-11的
var day=today.getDate();//获得当前日
var days=0;
//先判断每个月应该有的天数
function count(){
if(month!=2){
if((month==4)||(month==6)||(month==9)||(month==11)){
days=30;
}else{
days=31;
}
}else{
if((year%4)==0&&(year%100)!=0||year%400==0){
days=29;
}else{
days=28;
}
}
}
//输出当前日期
function showMonth(){
var year_month=year+"年"+month+"月"+day+"日";
document.getElementById("dqrq").innerHTML=year_month;
}
function showDate(){
showMonth();
count();
var firstdate=new Date(year,month-1,1);
var xq=firstdate.getDay();
var daterow=document.getElementById("day");
daterow.innerHTML="";
if(xq!=0){
for(var i=0;i<xq;i++){
var dayElement=document.createElement("div");
dayElement.className="everyday";
daterow.appendChild(dayElement);
}
}
for(var j=1;j<=days;j++){
var dayElement=document.createElement("div");
dayElement.className="everyday";
dayElement.innerHTML=j+"";
if(j==day){
dayElement.style.color="red";
}
daterow.appendChild(dayElement);
}
}
//上个月
function lastMonth(){
if(month>1) {
month=month-1;
}else{
month=12;
year=year-1;
}
showDate();
}
//下个月
function nextMonth(){
if(month<12) {
month=month+1;
}else{
month=1;
year=year+1;
}
showDate();
}