原生js日历小插件

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinat_34603663/article/details/81592283

日历

很久以前的一段代码,再来记个笔记:
这里写图片描述
完整代码:

<!HTML>
<head>
  <style>
     /* 整体设置 */
*{margin:0px;padding:0px;}
 .wrapper{
   width:668px;
   height:488px;
   margin:60px auto;
   border:1px solid #dddddd;
 }
 .calendar{

 }
 .calendar-title-box{
    height:50px;
    background:#f0f0f0;
 }
 #calendarTable{
   width:100%;
   padding:0 20px 10px;
   border-spacing:0;
 }
 #calendarTable tr th{height:50px;border-bottom:2px solid #dddddd;}
 #calendarTable td{text-align:center;height:60px;}
 .otherMonth{
     color:#c8c8c8;
 }
 .currentDay{
     background:#ff7637;
     color:#fff;
 }
 .cal_selectyear{
   padding:5px 10px;
   margin:10px;
   border:1px solid #dddddd;
   float:left;
   height:30px;
 }
 .cal_month{
    float:left;
    margin:10px 0;
    height:30px;
 }
 .cal_month span{
    float:left;
    border:1px solid #dddddd;
    height:28px;
    width:28px;
    background:#fff;
    text-align:center;
    line-height:26px;
    cursor:pointer;
 }
 .cal_month select{
   float:left;
   padding:5px 10px;
   height:30px;
   border:1px solid #dddddd;
   border-left:0;
   border-right:0;
 }
 th.week{
    color:#ff7637;
    border-color:#ff7637 !important;
 }
 .currentMonth.week{
    color:#ff7637;
    border-color:#ff7637 !important;
 }
  td.haveclass{
    position:relative;
  }
  td.haveclass:after{
   content:"";
   display:block;
   width:10px;
   height:10px;
   position:absolute;
   top:10px;
   right:24px;
   background:#ff7637;
   border-radius:50%;
 }
 .calendar-title-box .today{
   float:right;
   height:28px;
   margin:10px;
   line-height:28px;
   border:1px solid #dddddd;
   background:#fff;
   font-size:14px;
   padding:0 24px;
   cursor:pointer;
   color:#ff7637;
 }

  </style>
</head>
<body>

  <div class="wrapper">
    <div class='calendar' id='calendar'></div>
    </div>
  </div>

  <script>

    function Ddv_calendar(option){
        this.oClendar = document.getElementById(option.id);
        this.click = option.click;
        this.change = option.change;
        this.data = option.data;
        this.titleBox = document.createElement("div");  // 标题盒子 设置上一月 下一月 标题
      this.bodyBox = document.createElement("div");  // 表格区 显示数据
      this.init();
      this.oNext = document.getElementById('ddv-next');
      this.oPrev = document.getElementById('ddv-prev');
      this.today = document.getElementById('ddv-today')
      this.btnEvt();
        var setyearchoose = function(num){
          var now = new Date().getFullYear();
          var now1 = parseInt(now);
          var arr = [];
          var arr1 = [];
          var selectYearHtml = "";
          for(var i=0;i<num/2;i++){
            arr1.push(now1)
            now1--;
            now++;
            arr.push(now)
          }
          var resarr = arr1.reverse().concat(arr);
          resarr.forEach(function(item,index){
            selectYearHtml += "<option value="+item+">"+item+"年</option>"
          })
          document.getElementById('cal_selectyear').innerHTML = selectYearHtml;
        }
        var setmonthchoose = function(){
           var selectMonth = '';
           for(var i=1;i<=12;i++){
              selectMonth += "<option value="+i+">"+i+"月</option>";
           }
          document.getElementById('cal_selectmonth').innerHTML = selectMonth;
        }
        setyearchoose(20);
        setmonthchoose();
        this.filldata(new Date());
    }
    Ddv_calendar.prototype = {
        /**
         * 日期转化为字符串, 4位年+2位月+2位日
         */
        getDateStr: function(date) {
            var _year = date.getFullYear();
            var _month = date.getMonth() + 1;    // 月从0开始计数
            var _d = date.getDate();

            _month = (_month > 9) ? ("" + _month) : ("0" + _month);
            _d = (_d > 9) ? ("" + _d) : ("0" + _d);
            return _year +'-'+ _month +'-'+ _d;
        },
        init: function(){
            var _this = this;
              this.titleBox.className = 'calendar-title-box';
              this.titleBox.innerHTML = '<select class="cal_selectyear" id="cal_selectyear"></select>'+
                                      '<div class="cal_month"><span id="ddv-prev"><</span><select style="margin:0;" id="cal_selectmonth"></select><span id="ddv-next">></span></div>'+
                                  '<span class="today" id="ddv-today">返回今天</span>';
              this.oClendar.appendChild(this.titleBox);    // 添加到calendar div中

              // 设置表格区的html结构
                this.bodyBox.className = 'calendar-body-box';
                var _headHtml = "<thead><tr>" +
                      "<th class='week'>SUN 日</th>" +
                      "<th>MUN 一</th>" +
                      "<th>TUE 二</th>" +
                      "<th>WED 三</th>" +
                      "<th>THU 四</th>" +
                      "<th>FRI 五</th>" +
                      "<th class='week'>SAT 六</th>" +
                    "</tr></thead>";
              var _bodyHtml = "";
            // 一个月最多31天,所以一个月最多占6行表格
                for(var i = 0; i < 6; i++) {
                  _bodyHtml += "<tr>" +
                          "<td></td>" +
                          "<td></td>" +
                          "<td></td>" +
                          "<td></td>" +
                          "<td></td>" +
                          "<td></td>" +
                          "<td></td>" +
                        "</tr>";
                }
            this.bodyBox.innerHTML = "<table id='calendarTable' class='calendar-table'>" +
                  _headHtml + _bodyHtml +
                  "</table>";
            // 添加到calendar div中
            this.oClendar.appendChild(this.bodyBox);

                this.addEvent(document.getElementById('calendarTable'),'click',this.click);
          this.addEvent(document.getElementById('cal_selectyear'),'change',this.change);
          this.addEvent(document.getElementById('cal_selectmonth'),'change',function(){});
        },
        filldata: function(dateObj,resdata){
          var _year = dateObj.getFullYear();
            var _month = dateObj.getMonth() + 1;
            var _dateStr = this.getDateStr(dateObj);
            // 设置顶部标题栏中的 年、月信息
            var titleYear = _dateStr.split('-')[0] + "年";
            var titleMonth = parseInt(_dateStr.split('-')[1]) + "月";
            var optionsY = document.getElementById('cal_selectyear').options;
            for(var i=0;i<optionsY.length;i++){
              if(optionsY[i].innerText==titleYear){
                optionsY[i].selected = true;
              }
            }
            var optionsM = document.getElementById('cal_selectmonth').options;
            for(var k=0;k<optionsM.length;k++){
              if(optionsM[k].innerText==titleMonth){
                optionsM[k].selected = true;
              }
            }
            // 设置表格中的日期数据
            var _table = document.getElementById("calendarTable");
            var _tds = _table.getElementsByTagName("td");
            var _firstDay = new Date(_year, _month - 1, 1);  // 当前月第一天
            for(var i = 0; i < _tds.length; i++) {
              var _thisDay = new Date(_year, _month - 1, i + 1 - _firstDay.getDay());
              var _thisDayStr = this.getDateStr(_thisDay);
              _tds[i].innerText = _thisDay.getDate();
              _tds[i].setAttribute('data', _thisDayStr);
              if(_thisDayStr == this.getDateStr(new Date())) {    // 当前天
                _tds[i].className = 'currentDay';
        }else if(_thisDayStr.split('-')[1] == this.getDateStr(_firstDay).split('-')[1] ) {
                _tds[i].className = 'currentMonth';  // 当前月
              }else {    // 其他月
                _tds[i].className = 'otherMonth';
              }
               if(_thisDay.getDay()==0 || _thisDay.getDay()==6){
                _tds[i].classList.add('week');

              }
              var fordata = resdata?resdata:this.data;
              if(fordata){
                fordata.forEach(function(item){
                    if(parseInt(item)==_thisDay.getDate()){
                       _tds[i].classList.add('haveclass');
                    }
                })
              }
            }
        this.change(dateObj);
        },
      btnEvt: function(){
          var _this = this;
          this.addEvent(this.oNext,'click',function(e) {
          var now = _this.getcuttentdate();
          var addy = +now.split('-')[0];
          var addm = +now.split('-')[1];
          addm++;
          if(addm>12){
            addm=1;
            addy++;
          }
          var last = addy+'-'+(addm>=10?addm:'0'+addm)+'-'+now.split('-')[2];
          _this.filldata(new Date(last));
        });
        this.addEvent(this.oPrev,'click',function(e) {
          var now = _this.getcuttentdate();
          var addy = +now.split('-')[0];
          var addm = +now.split('-')[1];
          addm--;
          if(addm<1){
            addm=12;
            addy--;
          }
          var last = addy+'-'+(addm>=10?addm:'0'+addm)+'-'+now.split('-')[2];
          _this.filldata(new Date(last));
        });
        this.addEvent(this.today,'click',function(e) {
          _this.filldata(new Date());
        })
      },
      getcuttentdate: function(){
        var year = document.getElementById('cal_selectyear').value;
        var month = document.getElementById('cal_selectmonth').value;
        var day = document.querySelector('.currentDay')?document.querySelector('.currentDay').innerText:1;
        var data = year +'-'+ (month<10?'0'+month:month) +'-'+ (day<10?'0'+day:day);
        return data;
      },
        addEvent: function(dom, eType, func) {
          var _this = this;
            if(dom.addEventListener) {  // DOM 2.0
                dom.addEventListener(eType, function(e){
              if(e.type=='change'){
                var data = _this.getcuttentdate();
                _this.filldata(new Date(data));
              }else{
                var data = e.target.getAttribute('data');
              }
              if(data){
                func(data);
              }else{
                func(e);
              }
                });
            } else if(dom.attachEvent){  // IE5+
                dom.attachEvent('on' + eType, function(e){
              if(e.type=='change'){
                var data = _this.getcuttentdate();
                _this.filldata(new Date(data));
              }else{
                        var data = e.target.getAttribute('data');
              }
              if(data){
                func(data);
              }else{
                func(e);
              }
                });
            } else {  // DOM 0
                  dom['on' + eType] = function(e) {
              if(e.type=='change'){
                var data = _this.getcuttentdate();
                _this.filldata(new Date(data));
              }else{
                        var data = e.target.getAttribute('data');
              }
              if(data){
                func(data);
              }else{
                func(e);
              }
                }
            }
        }
    }
    var calendar = new Ddv_calendar({
      id:'calendar',
        click: function(data){
          console.log(data)
        //查询单天的信息
        },
      change: function(data){
        console.log(data)
        //设置动态的初始数据
      }
    });

    // setTimeout(function(){
    //    calendar.filldata(new Date(),['03','15','31'])
    // },1000)

  </script>
</body>
</html>
阅读更多

没有更多推荐了,返回首页