教你用js實現日曆功能(附程式碼範例)

2022-08-06 10:00:10


範例程式碼

<template>
  <div id="calendar">
    <!-- 年份 月份 -->
    <div class="month">
      <ul>
        <!--點選會觸發pickpre函數,重新重新整理當前日期 @click(vue v-on:click縮寫) -->
        <li
          class="arrow hands el-icon-arrow-left"
          @click="pickPre(currentYear, currentMonth)"
        ></li>
        <li class="year-month">
          <span class="choose-year">{{ currentYear }}年</span>
          <span class="choose-month">{{ currentMonth }}月</span>
        </li>
        <li
          class="arrow hands el-icon-arrow-right"
          @click="pickNext(currentYear, currentMonth)"
        ></li>
      </ul>
    </div>
    <!-- 星期 -->
    <ul class="weekdays">
      <li>日</li>
      <li>一</li>
      <li>二</li>
      <li>三</li>
      <li>四</li>
      <li>五</li>
      <li>六</li>
    </ul>
    <!-- 日期 -->
    <ul class="days">
      <!-- 核心 v-for迴圈 每一次迴圈用<li>標籤建立一天 -->
      <li v-for="(dayobject, i) in days" :key="i">
        <!--本月-->
        <!--如果不是本月  改變類名加灰色-->
        <span
          v-if="dayobject.day.getMonth() + 1 != currentMonth"
          class="other-month"
          @click="getDayTime(dayobject.day)"
        >
          {{ dayobject.day.getDate() }}
        </span>
        <!--如果是本月  還需要判斷是不是這一天-->
        <span v-else>
          <!--今天  同年同月同日-->
          <span
            v-if="
              dayobject.day.getFullYear() == new Date().getFullYear() &&
              dayobject.day.getMonth() == new Date().getMonth() &&
              dayobject.day.getDate() == new Date().getDate()
            "
            :class="newDate == newsss ? 'active' : ''"
            @click="getDayTime(dayobject.day, i)"
          >
            {{ dayobject.day.getDate() }}
          </span>
          <span
            v-else
            @click="getDayTime(dayobject.day, i)"
            :class="newDate == dayobject.day ? 'active' : ''"
          >
            {{ dayobject.day.getDate() }}
          </span>
        </span>
      </li>
    </ul>
  </div>
</template>
<script>
export default {
  data() {
    return {
      currentDay: 1,
      currentMonth: 1,
      currentYear: 2021,
      currentWeek: 1,
      days: [],
      newDate: this.$formatDateYMD(new Date()),
      newsss: this.$formatDateYMD(new Date()),
    };
  },
  created: function () {
    // 在vue初始化時呼叫
    this.initData(null);
  },
  methods: {
    initData: function (cur) {
      // var leftcount = 0 // 存放剩餘數量
      var date;
      if (cur) {
        date = new Date(cur);
      } else {
        var now = new Date();
        var d = new Date(this.formatDate(now.getFullYear(), now.getMonth(), 1));
        d.setDate(35);
        date = new Date(this.formatDate(d.getFullYear(), d.getMonth() + 1, 1));
      }
      this.currentDay = date.getDate();
      this.currentYear = date.getFullYear();
      this.currentMonth = date.getMonth() + 1;
      this.currentWeek = date.getDay(); // 1...6,0
      if (this.currentWeek === 0) {
        this.currentWeek = 7;
      }
      var str = this.formatDate(this.currentYear, this.currentMonth, this.currentDay);
      this.days.length = 0;
      // 今天是週日,放在第一行第7個位置,前面6個
      // 初始化本週
      for (var i = this.currentWeek; i >= 0; i--) {
        var d2 = new Date(str);
        d2.setDate(d2.getDate() - i);
        var dayobjectSelf = {}; // 用一個物件包裝Date物件  以便為以後預定功能新增屬性
        dayobjectSelf.day = d2;
        this.days.push(dayobjectSelf); // 將日期放入data 中的days陣列 供頁面渲染使用
      }
      // 其他周
      for (var j = 1; j <= 35 - this.currentWeek; j++) {
        var d3 = new Date(str);
        d3.setDate(d3.getDate() + j);
        var dayobjectOther = {};
        dayobjectOther.day = d3;
        this.days.push(dayobjectOther);
      }
    },
    getDayTime(el, index) {
      this.newDate = el;
      console.log(el)
    },
    pickPre: function (year, month) {
      // setDate(0); 上月最後一天
      // setDate(-1); 上月倒數第二天
      // setDate(dx) 引數dx為 上月最後一天的前後dx天
      var d = new Date(this.formatDate(year, month, 1));
      d.setDate(0);
      this.initData(this.formatDate(d.getFullYear(), d.getMonth() + 1, 1));
    },
    pickNext: function (year, month) {
      var d = new Date(this.formatDate(year, month, 1));
      d.setDate(35);
      this.initData(this.formatDate(d.getFullYear(), d.getMonth() + 1, 1));
    },
    // 返回 類似 2022-05-17 格式的字串
    formatDate: function (year, month, day) {
      var y = year;
      var m = month;
      if (m < 10) m = "0" + m;
      var d = day;
      if (d < 10) d = "0" + d;
      return y + "-" + m + "-" + d;
    },
  },
};
</script>
<style>
#calendar {
  font-size: 12px;
  width: 100%;
  margin: 0 auto;
  background: #ecf6ff;
}
.month {
  width: 100%;
  color: #333333;
}
.month ul {
  margin: 0;
  padding: 0;
  display: flex;
  justify-content: space-between;
  height: 35px;
}
.year-month {
  display: flex;
  align-items: center;
  justify-content: space-around;
  margin-top: 10px;
}
.choose-month {
  text-align: center;
  font-size: 12px;
}
.arrow {
  padding: 15px;
  color: #999999;
}
 
.month ul li {
  font-size: 12px;
  text-transform: uppercase;
  letter-spacing: 3px;
}
.weekdays {
  margin: 0;
  padding: 10px;
  display: flex;
  flex-wrap: wrap;
  color: #999;
  justify-content: space-around;
}
.weekdays li {
  display: inline-block;
  width: 13.6%;
  text-align: center;
}
.days {
  padding: 10px;
  margin: 0;
  display: flex;
  flex-wrap: wrap;
}
.days li {
  list-style-type: none;
  display: inline-block;
  width: 14.2%;
  text-align: center;
  padding-bottom: 4px;
  padding-top: 10px;
  font-size: 12px;
  color: #000;
}
.days li .active {
  padding: 6px 10px;
  border-radius: 50%;
  background: #00b8ec;
  color: #fff;
}
.days li .other-month {
  padding: 5px;
  color: gainsboro;
}
.days li:hover > span > span {
  padding: 6px 10px;
  border-radius: 50%;
  background: #00b8ec;
  color: #fff;
  cursor: pointer;
}
</style>

注意:在執行過程中可能會出現一點小問題,這裡我用到了一個日期處理類庫 moment.js,如需安裝請執行以下命令安裝moment.js外掛,在main.js 全域性設定。

npm install moment --save

main.js

import Vue from 'vue'
import Moment from 'moment';
Vue.prototype.$Moment = Moment;
Vue.prototype.$formatDateYMD = function(date) {
    return Moment(date).format('YYYY-MM-DD')
}

相關推薦:【】

以上就是教你用js實現日曆功能(附程式碼範例)的詳細內容,更多請關注TW511.COM其它相關文章!