有些时候我们翻看别人的博客的时候,会发现有一个日历面板,可以点击左右按钮查看上下个月的日历,那么这是怎么实现的呢?其实并不难,主要就是用javascript的date()方法。
先看效果图:
具体代码:
html
<div class="box">
<div class="date">
<div class="title">
<span class="last" id="showLastMonth"><</span>
<div class="current">
<span id="showYear"></span>
<span>/</span>
<span id="showMonth"></span>
</div>
<span class="next" id="showNextMonth">></span>
</div>
<div class="xq">
<ul>
<li>日</li>
<li>一</li>
<li>二</li>
<li>三</li>
<li>四</li>
<li>五</li>
<li>六</li>
</ul>
</div>
<div class="day">
<ul id="showDay">
</ul>
</div>
</div>
</div>
css样式
ul{list-style: none;margin: 0;padding: 0;overflow: hidden;}
ul li{float: left;width: 30px;height: 30px;line-height: 30px;margin: 5px;text-align: center;border-radius: 50%;}
ul .today{background: #FD6639;color: #FFF;}
.day li{font-size: 15px;}
.day li:hover{color: #00F;cursor: pointer;}
.box{width: 280px;border: 1px solid #DDD;}
.xq{background: #E7F1FD;}
.title{background: #7AB2ED;height: 40px;line-height: 40px;}
.title .last{float: left;width: 40px;text-align: center;cursor: pointer;}
.title .next{float: right;width: 40px;text-align: center;cursor: pointer;}
.title .current{text-align: center;width: 200px;float: left;color: #FFF;}
.title .last:hover{color: #FD6639;background: rgba(0,0,0,0.2);}
.title .next:hover{color: #FD6639;background: rgba(0,0,0,0.2);}
javascript
<script type="text/javascript">
var date = new Date();
var year = date.getFullYear();//年
var month = date.getMonth();//月(0-11)
var currentY = year;
var currentM = month;
var currentD = date.getDate();
showDate(date);
var lastBtn = document.getElementById("showLastMonth");
var nextBtn = document.getElementById("showNextMonth");
lastBtn.onclick = function(){
if(month==0){
year-=1;
month=11;
}else{
month--;
}
showDate(new Date(year,month,1));
}
nextBtn.onclick = function(){
if(month==11){
year+=1;
month=0;
}else{
month++;
}
showDate(new Date(year,month,1));
}
function showDate(obj){
var year = obj.getFullYear();//年
var month = obj.getMonth();//月
//var date = obj.getDate();//日
var sDay = new Date(year,month,1).getDay();//本月第一天星期几
var days = new Date(year,month+1,0).getDate();//本月一共多少天
document.getElementById("showYear").innerHTML = year;
document.getElementById("showMonth").innerHTML = month+1;
var dayObj = document.getElementById("showDay");
var htmlStr = "";
for (var i = 1; i <= sDay; i++) {
htmlStr += "<li></li>";
}
for (var i = 1; i <= days; i++) {
if(currentY == year && currentM == month && i == currentD){
htmlStr += "<li class='today'>"+i+"</li>";
}else{
htmlStr += "<li>"+i+"</li>";
}
}
dayObj.innerHTML = htmlStr;
}
</script>
有些博客加入了这么一个功能:在有博文的日历上做了一个标记,表示在当日有博文发表,那么这个我们可以用ajax来实现,再重绘日历的时候获取当月有文章的日期,然后加入样式。