日历基本效果实现

原创 heliang090034 随笔 JS 240阅读 2017-12-02 17:01:38 举报

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>日历</title>
<style type="text/css">
body,ul,li{
padding: 0;
margin: 0;
}
.table{
width: 300px;
height: 300px;
margin: 30px auto;
position: relative;
text-align: center;
}
.table .theader{
list-style: none;
position: relative;
top: 0;
width: 100%;
margin-right: -1px;
}
.table .theader div,.table .tbody div{
float: left;
width: 13%;
margin-top: -1px;
margin-right: -1px;
height: 13%;
line-height: 39px;
border:1px solid #ccc;
overflow: hidden
}
.table .tbody{
height:90%;
}
</style>
</head>
<body>
<button onclick="getChangeMonth('add')">next</button>
<button onclick="getChangeMonth()">pre</button>
<div class="table">
<p>当前时间<span id="no"></span></p>
<div class="theader">
<div>日</div>
<div>一</div>
<div>二</div>
<div>三</div>
<div>四</div>
<div>五</div>
<div>六</div>
</div>
<div class="tbody" id='tbody'></div>
</div>
<script type="text/javascript">
var tbody=document.querySelector('#tbody');
var no=document.querySelector('#no');
function Calendar(){
this.months=[];
this.year="";
this.month="";
this.currentDay="";
}
Calendar.prototype.init=function(){
this.loadTime();
}
Calendar.prototype.isLeap=function(year){
if((year%4==0&&year%100!=0)||(year%400==0)){
return true;
}else{
return false;
}
}
Calendar.prototype.loadTime=function(time){
var timeDate;
if(time){
timeDate=time;
}else{
timeDate=new Date();
}
this.year= timeDate.getFullYear();
this.months=[31,this.isLeap(this.year)?29:28,31,30,31,30,31,31,30,31,30,31];
this.month= timeDate.getMonth();
this.currentDay=timeDate.getDate();
this.rednerCandler();
}
//
Calendar.prototype.changeDate=function(type){
console.log(this.year,this.month,this.currentDay)
var date=new Date(this.year+'-'+(this.month+1)+'-'+this.currentDay)
if(type=="add"){
date.setMonth(this.month+1);
}else{
if(type!="init"){
date.setMonth(this.month-1);
}
}
this.loadTime(date);
}
Calendar.prototype.rednerCandler=function(year,month,currentDay){
var html="";
var style="";
var firstMonthOfDay=new Date(this.year,this.month,1).getDay();
var maxDays=this.months[this.month];
var curDay=new Date().getDate();
var curMonth=new Date().getMonth();
var curYear=new Date().getFullYear();
for(var i=0;i<6;i++){
for(var j=0;j<7;j++){
var index=(i*7)+j-firstMonthOfDay+1;
if(index<=0||index>maxDays){
html+="<div class='noData'></div>";
}else{
((curDay==index)&&curMonth==this.month&&this.year==curYear)?style="background:red;":style="";
html+="<div style='"+style+"'>"+index+"</div>";
}
}
}
tbody.innerHTML="";
tbody.innerHTML=html;
}
let calendar=new Calendar();
calendar.init();
getChangeMonth('init');
function getChangeMonth(type){
var no=document.querySelector('#no');
calendar.changeDate(type);
no.innerHTML=calendar.year+"-"+(calendar.month+1);
}
</script>
</body>
</html>

评论 ( 0 )
最新评论
暂无评论

赶紧努力消灭 0 回复