以前在开发web页面的时候遇到日历,都是直接引入一些日历组件来用,一直不太明白实现原理,总感觉挺复杂的。

今天尝试着用jquery写了一个简单的日历功能,可以选择年份,月份,返回今天,原来简单的日历功能自己也是可以写的。至于日历中的其他一些强大功能相信只要努力,也是可以实现的。

下面贴出实现的代码,供小伙伴们参考,希望对你们有一些帮助。

一、首页是html代码,其中的css,js引入路径和文件名需要自己改一下,其中我用的是jquery的1.8.3,可以引入其他更高版本,自行引入。

1 <!DOCTYPE html>
 2 <html lang="en">
 3 <head>
 4     <meta charset="UTF-8">
 5     <title>日历</title>
 6     <link rel="stylesheet" href="css/style.css">
 7     <script src="js/jquery-1.8.3.min.js"></script>
 8     <script src="js/demo.js"></script>
 9 </head>
10 <body>
11     <div class="main clearfix">
12         <div class="menu clearfix">
13             <div class="select fl pr">
14                 <ul class="select-list select-year pa none">
15                     <li value="2015">2015年</li>
16                     <li value="2016">2016年</li>
17                     <li value="2017">2017年</li>
18                 </ul>
19                 <div class="select-text year"><span class="year-text" value="2016">2016年</span>▼</div>
20             </div>
21             <a class="select-prev fl" href="javascript:;"><</a>
22             <div class="select month fl pr">
23                 <ul class="select-list pa none">
24                     <li value="1">1月</li>
25                     <li value="2">2月</li>
26                     <li value="3">3月</li>
27                     <li value="4">4月</li>
28                     <li value="5">5月</li>
29                     <li value="6">6月</li>
30                     <li value="7">7月</li>
31                     <li value="8">8月</li>
32                     <li value="9">9月</li>
33                     <li value="10">10月</li>
34                     <li value="11">11月</li>
35                     <li value="12">12月</li>
36                 </ul>
37                 <div class="select-text"><span class="month-text" value="1">1月</span>▼</div>
38             </div>
39             <a class="select-next fl" href="javascript:;">></a>
40             <a class="select-today fl" href="javascript:;">返回今天</a>
41             <div class="time fl">10:40:05</div>
42         </div>
43         <ul class="title">
44             <li>日</li><li>一</li><li>二</li><li>三</li><li>四</li><li>五</li><li>六</li>
45         </ul>
46         <ul class="table">
47             <li><span>1</span></li><li><span>2</span>
48         </ul>
49     </div>
50 </body>
51 </html>

二、接下来是css样式

1 *{margin:0;padding: 0;font-family: '微软雅黑';}
 2 body{background: #fff;}
 3 ul{list-style: none;}
 4 a{text-decoration: none;color:#333;}
 5 img{border:none;}
 6 .fl{float:left;_display:inline;}
 7 .fr{float:right;_display:inline;}
 8 .pr{position: relative;}
 9 .pa{position: absolute;}
10 .none{display: none;}
11 .clearfix:before,.clearfix:after{content:"";display:table;}
12 .clearfix:after{clear:both;}
13 .clearfix{*zoom:1;}
14 
15 .main{width:385px;margin:20px auto;padding:10px;border:2px #57abff solid;color:#333;}
16 .menu{font-size: 14px;}
17 .select{width:80px;height:25px;line-height:25px;border:1px #d8d8d8 solid;cursor: default;}
18 .select-text{text-align: center;}
19 .select-text:hover{box-shadow: 1px 1px 0 0 #d8d8d8 inset;}
20 .select div.current{box-shadow: 1px 1px 0 0 #d8d8d8 inset;}
21 .month{border-left:none;border-right:none;}
22 .select-list{left:-1px;top:25px;width: 80px;max-height:360px;background: #fff;border:1px #d8d8d8 solid;overflow: auto;}
23 .select-list li{height: 30px;line-height: 30px;text-indent: 10px;cursor: pointer;}
24 .select-list li.selected{background: #d8d8d8;}
25 .select-list li.on{background: #d8d8d8;}
26 .select-prev,.select-next{width:25px;height: 25px;margin-left:10px;line-height: 25px;text-align: center;border:1px #d8d8d8 solid;cursor: pointer;}
27 .select-next{margin:0;}
28 .select-today{width:80px;height: 25px;margin-left:10px;line-height: 25px;text-align: center;border:1px #d8d8d8 solid;cursor: pointer;}
29 .select-prev:hover,.select-next:hover,.select-today:hover{border:1px #57abff solid;}
30 .select-prev:active,.select-next:active,.select-today:active{background: #f0f0f0;box-shadow: 1px 1px 1px #c7c7c7 inset;}
31 .time{height: 25px;margin-left:10px;line-height: 25px;}
32 .title{height:35px;font-size: 16px;margin-top:10px;border-top:1px #57abff solid;}
33 .title li{float:left;width:55px;height:35px;line-height: 35px;text-align: center;}
34 .table li{float:left;width:55px;height:55px;border-bottom: 1px #c8cacc solid;font-size: 18px;cursor: pointer;}
35 .table li span{display: block;width:51px;height:51px;line-height: 51px;text-align: center;border:2px #fff solid;}
36 .table li span.on{border:2px #fb0 solid;}
37 .table li span.today{background: #fb0;border:2px #fb0 solid;color:#fff;}

三、最后是js了,相信熟悉jquery的都感觉很简单,不太熟悉的可以多看看jquery手册,挺简单的。

1 $(function(){
  2     var init = {
  3         startYear: 1900, //年份列表开始年
  4         endYear: 2050 //年份列表结束年
  5     };
  6     var fun = {
  7         init: function(){
  8             this.showYear();
  9             this.timeBox();
 10             this.dateBox();
 11         },
 12         showYear: function(){ //循环年列表
 13             var startYear = init.startYear,
 14                 endYear = init.endYear,
 15                 yearHtml = '';
 16             for(;startYear <= endYear; startYear++){
 17                 yearHtml += '<li value="'+startYear+'">'+startYear+'年</li>';
 18             };
 19             $('.select-year').html(yearHtml);
 20         },
 21         timeBox: function(){ //系统时间
 22             (function(){
 23                 var date = new Date();
 24                 var h = date.getHours(),
 25                     m = date.getMinutes(),
 26                     s = date.getSeconds();
 27                 var time = h + ':' + m + ':' + s;
 28                 var time = fun.timeBu(time);
 29                 $('.time').html(time);
 30                 setTimeout(arguments.callee, 1000);
 31             })();
 32         },
 33         timeBu: function(val){
 34             var arr = val.split(':');
 35             for(var i = 0; i < arr.length; i++){
 36                 if(arr[i] < 10){
 37                     arr[i] = '0' + arr[i];
 38                 }
 39             };
 40             return arr.join(':');
 41         },
 42         showDate: function(year, month){ //日历展示
 43             //改变下拉
 44             $('.year-text').text(year + '年').attr('value', year);
 45             $('.month-text').text(month + '月').attr('value', month);
 46             $('.select-list li').removeClass('selected');
 47             //为当前已经默认的年份和有份标为选中
 48             $('.select-list li').addClass(function(i){
 49                 var value = $(this).attr('value');
 50                 if(value == year || value == month){
 51                     return 'selected';
 52                 }
 53             });
 54 
 55             var setDate = new Date();
 56             setDate.setFullYear(year); //设置年份
 57             setDate.setMonth(month-1); //设置月份,因为系统的月份都是比真实的小1
 58             setDate.setDate(1); //设置成当前月第一天
 59 
 60             var num = setDate.getDay(); //得到本月第一天是星期几
 61 
 62             setDate.setMonth(month); //设置成正确的真实月份
 63             var lastDate = new Date(setDate.getTime() - 1000*60*60*24); //计算得到当前月最后一天的日期格式
 64             var lastDay = lastDate.getDate(); //获取本月最后一天是几号
 65 
 66             //利用得到的当前月总天数来循环出当前月日历
 67             var html = '';
 68             for(var i = 1; i <= lastDay; i++){
 69                 html += '<li><span>'+i+'</span></li>';
 70             };
 71             $('.table').html(html);
 72 
 73             var first = $('.table li:first'),
 74                 w = first.outerWidth();
 75             first.css('marginLeft', w * num + 'px'); //根据得到的本月第一天是周几得出第一个li所在的位置,从而排列好整个日历
 76 
 77             var nowDate = new Date(), //得到系统当前的真实时间
 78                 nowYear = nowDate.getFullYear(),
 79                 nowMonth = nowDate.getMonth() + 1,
 80                 today = nowDate.getDate(); //获取当前是几号
 81             if(nowYear == year && nowMonth == month){ //验证当前展示中是否包含今天
 82                 $('.table li').eq(today-1).find('span').addClass('today'); //标出今天
 83             }
 84             
 85         },
 86         dateBox: function(){
 87             var date = new Date(),
 88                 year = date.getFullYear(), //获取当前是哪一年
 89                 month = date.getMonth() + 1; //获取当前月
 90             
 91             //初始化日历
 92             fun.showDate(year, month);
 93             
 94         }
 95     }
 96     fun.init(); //运行
 97     //下拉选择
 98     $('.select-text').on('click', function(e){
 99         e.stopPropagation();
100         var self = $(this);
101         self.toggleClass('current');
102         self.parent().siblings('.select').find('.select-list').hide();
103         self.prev().toggle();
104         //点击是的年份时则始终保持已经选中的年在第一位
105         if(self.hasClass('year')){
106             $('.select-year').scrollTop(0);
107             var top = $('.select-year .selected').position().top;
108             $('.select-year').scrollTop(top);
109         }
110     });
111     //下拉悬浮
112     $('.select-list li').on({
113         'mouseenter': function(){
114             $(this).addClass('on');
115         },
116         'mouseleave': function(){
117             $(this).removeClass('on');
118         }
119     });
120     $(document).on('click', function(){
121         $('.select-list').hide();
122         $('.select-text').removeClass('current');
123     });
124     //切换年,月
125     $('.select-list li').on('click', function(){
126         if($(this).hasClass('selected')){ //如果是已经选中的则不用在重新初始化日历
127             return;
128         };
129         var self = $(this),
130             text = self.text(),
131             value = self.attr('value');
132         self.addClass('selected').siblings().removeClass('selected');
133         self.parent().next().find('span').text(text).attr('value', value);
134         var year = $('.year-text').attr('value'),
135             month = $('.month-text').attr('value');
136         fun.showDate(year, month);
137     });
138 
139     //返回今天
140     $('.select-today').on('click', function(){
141         
142         fun.dateBox();
143     });
144 
145     //日期选择
146     //日期悬浮时
147     $('body').on({
148         'mouseenter': function(){
149             $(this).addClass('on');
150         },
151         'mouseleave': function(){
152             $(this).removeClass('on');
153         }
154     }, '.table span');
155     //点击日期
156     $('body').on('click', '.table span', function(){
157         var year = $('.year-text').attr('value'),
158             month = $('.month-text').attr('value'),
159             day = $(this).text();
160         var date = year + '-' + month + '-' + day;
161         alert(date);
162     });
163 
164     //前一个月
165     $('.select-prev').on('click', function(){
166         var year = parseInt($('.year-text').attr('value')),
167             month = parseInt($('.month-text').attr('value'));
168         if(month - 1 > 0){
169             month = month - 1;
170         }else{
171             month = 12;
172             year = year - 1;
173             if(year < init.startYear){
174                 return;
175             }
176         };
177         fun.showDate(year, month);
178     });
179     //后一个月
180     $('.select-next').on('click', function(){
181         var year = parseInt($('.year-text').attr('value')),
182             month = parseInt($('.month-text').attr('value'));
183         if(month + 1 <= 12){
184             month = month + 1;
185         }else{
186             month = 1;
187             year = year + 1;
188             if(year > init.endYear){
189                 return;
190             }
191         };
192         fun.showDate(year, month);
193     })
194 
195 })

 

将html,css,js都复制下来,放入到自己建立的对应文件中,注意把html中的引入路径修改对,别忘记引入jquery哦,最后只要双击打开html页面即可查看了。

这是最终效果图

javascript 日历 简单 jquery日历_css

相信明白后你也可以写出自己需要的日历功能。