DIV CSS 佈局教程網

自己寫一個 JavaScript 日曆控制項(基於 pj 庫)
編輯:關於JavaScript     

使用方式

先後引入 pj 庫與 Calendar.js,接著建立物件、掛事件、定位即可。

<script type="text/javascript" src="https://users4.Jabry.com/pengju/src/pj-2.1.1.mini.js"></script>
<script type="text/javascript" src="https://users4.Jabry.com/pengju/src/Calendar.js"></script>

<input name="" type="text" id="pos"
       style="position:absolute; left:200px; top:80px;" value="" readonly="readonly" />

<script type="text/javascript">
// 指定初始日期與年份下拉列表長度
var cat = new Calendar(new Date(1633, 6, 6), 100);
cat.onChange(function () { alert(this.getDateString()) });
cat.onSelect(function () { alert(this.getDateString()); });
cat.fadeIn(0);

// 綁到輸入框:點擊時顯示,選日期後寫回並隱藏
var o = new Calendar();
o.locateAt(pj.id("pos"));
o.onSelect(function () {
    pj.id("pos").value = this.getDateString();
    this.hide();
});
pj("#pos").focus(function () { o.show(100) });
</script>

最精簡的用法只需兩步:

var calendar = new Calendar();
calendar.show();

但 show() 其實是呼叫 pj 庫的方法,所以使用之前必須先引入 pj,再引入 Calendar.js。

API 一覽

方法

  • getDateString([pattern]):取得格式化日期字串,預設 yyyy-mm-dd。
  • show(duration):顯示日曆。
  • hide(duration):隱藏日曆。
  • fadeIn(duration):淡入。
  • fadeOut(duration):淡出。
  • locateAt(obj, offsetX, offsetY):把日曆定位到指定元素的正下方,offsetX/offsetY 可選,為相對 X、Y 軸的偏移量。

事件

  • onChange(fn):切換年份或月份時觸發,以當前 Calendar 物件為上下文執行 fn。
  • onSelect(fn):選擇日期時觸發,同樣以當前 Calendar 物件為上下文。

核心實作

建構器

// date: 預設起始日期,可為 null(則以當天開始)
// yearListLength: 年份下拉列表長度
function Calendar(date, yearListLength) {
    var currentDate = date || new Date(), _this = this;

    // 建立外層容器
    this.container = pj("<div>").appendTo(document.body).setStyle({
        overflow: 'hidden', background: '#99CCFF', border: '1px solid #CCC',
        fontSize: '12px', height: '160px', width: '180px',
        position: "absolute", display: 'none'
    });

    // 注入表格結構:上方是年份/月份下拉與切換,下方是星期標題與 6 列 7 欄的日期格
    this.container.get().innerHTML = '<table> ... </table>';

    this.spans   = pj("span", this.container.get());
    this.as      = pj("a", this.container.get()).setStyle({ textDecoration: "none", color: "#333" });
    this.selects = pj("select", this.container.get());

    this.getCurrentDate = function () { return currentDate; };
    this.init();
    this.initYearList(yearListLength || 70);

    var change = function () {}, select = function () {};
    this.onChange = function (fn) { if (pj.isFunction(fn)) change = fn; };
    this.onSelect = function (fn) { if (pj.isFunction(fn)) select = fn; };

    // 切換年份
    this.selects[0].onchange = function () {
        currentDate.setFullYear(parseInt(this.options[this.selectedIndex].value));
        _this.init();
        change.apply(_this, arguments);
    };
    // 切換月份
    this.selects[1].onchange = function () {
        currentDate.setMonth(parseInt(this.options[this.selectedIndex].value) - 1);
        _this.init();
        change.apply(_this, arguments);
    };
    this.selects[1].options[currentDate.getMonth()].selected = true;

    // 日期格的事件委派
    this.as.addListener({
        click:     function () {
            currentDate.setDate(parseInt(this.innerHTML));
            select.apply(_this, arguments);
        },
        mouseover: function () {
            if (_this.todate.getDate() + "" != this.innerHTML) this.style.color = "#CCC";
        },
        mouseout:  function () {
            if (_this.todate.getDate() + "" != this.innerHTML) this.style.color = "#333";
        }
    });

    // 儲存格底色變化
    pj("td", this.container.get(0)).addListener({
        mouseover: function () { this.style.backgroundColor = "#303"; },
        mouseout:  function () { this.style.backgroundColor = "#9CF"; }
    });
}

渲染當月

Calendar.prototype = {
    init: function () {
        var cur = this.getCurrentDate(),
            i = new Date(cur.getFullYear(), cur.getMonth(), 1).getDay(),      // 該月一號是星期幾
            j = new Date(cur.getFullYear(), cur.getMonth() + 1, 0).getDate(); // 該月總天數

        this.spans[0].innerHTML = cur.getFullYear();
        this.spans[1].innerHTML = cur.getMonth() + 1;

        var m = 0, n = this.as.length - 1, isTodate = Calendar.isThisMonth(cur);
        while (m < n) {   // 清空日期格
            this.as[m].innerHTML = this.as[n].innerHTML = '';
            n--; m++;
        }
        for (var day = 1; day <= j; day++, i++) {
            this.as[i].innerHTML = day;
            if (isTodate && day == this.todate.getDate()) {
                this.todateLink = this.as[i];   // 標記今天
                pj.setStyle(this.as[i], { color: "#F60", fontWeight: "bold" });
            }
        }
    },

    initYearList: function (len) {
        Calendar.emptySelect(this.selects[0]);
        var cur = this.getCurrentDate(),
            now = this.todate.getFullYear(),
            max = Math.max(now - cur.getFullYear(), len);
        for (var y = 0; y <= max; y++) {
            var option = document.createElement("option");
            option.selected = (cur.getFullYear() == now);
            option.text = now;
            option.value = now--;
            try { this.selects[0].add(option, null); }
            catch (e) { this.selects[0].add(option); }   // 舊 IE 的 add 只收一個參數
        }
    },

    getDateString: function (format) {
        if (!format || !/y{4}.m{2}.d{2}/.test(format)) format = "yyyy-mm-dd";
        format = format.replace(/^yyyy/, this.getCurrentDate().getFullYear());
        format = format.replace(/mm/, Calendar.fx(this.getCurrentDate().getMonth() + 1));
        format = format.replace(/dd/, Calendar.fx(this.getCurrentDate().getDate()));
        return format;
    },

    todate: new Date(),
    todateLink: null,

    show:     function (duration) { this.container.show(duration); },
    hide:     function (duration) { this.container.hide(duration); },
    fadeIn:   function (duration) { this.container.fadeIn(duration); },
    fadeOut:  function (duration) { this.container.fadeOut(duration); },
    locateAt: function (obj, offsetX, offsetY) {
        this.container.locate(obj, pj.LEFT_BOTTOM_POSITION, offsetX, offsetY);
    }
};

// 工具函式
Calendar.emptySelect = function (target) {
    if (!target.options) return;
    while (target.options.length > 0) target.remove(0);
};
Calendar.fx = function (dig) { return dig < 10 ? '0' + dig : dig; };   // 補零
Calendar.isThisMonth = function (date) {
    return date.getFullYear() == Calendar.prototype.todate.getFullYear() &&
           date.getMonth()    == Calendar.prototype.todate.getMonth();
};

幾個設計細節值得學

用 Date 的溢出特性算月份長度。new Date(y, m + 1, 0).getDate() 是求「某月有幾天」的經典技巧——第 0 天會回退到上個月的最後一天。

用 _this 保存 this。在事件處理器與 setTimeout 的匿名函式中,this 會被重新綁定,所以必須先把外層的 this 存成區域變數。

事件委派。把 click 掛在包含所有日期格的容器上,透過 pj 的 addListener 統一處理,比替 42 個 a 標籤各掛一次要乾淨。

select.add 的 try/catch。舊版 IE 的 add 只接受一個參數,這是刻意的相容處理。

今日的建議

範例中的 pj 庫與其託管網址(users4.Jabry.com)早已失效,Calendar.js 也依賴它,因此這份程式碼無法直接運行。若只是要一個日曆元件,現階段更務實的選擇是:

  • 使用成熟函式庫:Flatpickr、Air Datepicker、react-datepicker 等,無需 jQuery 依賴、具備國際化與可及性支援。
  • 或直接打字串的 date/time 輸入型別,行動裝置上會叫出原生日期選擇器。

但若目的是練習,這個範例在「如何用原生 Date 運算日期、如何用事件委派管理大量格位、如何把 this 正確傳遞進回呼」這幾件事上,仍然很值得一读。

XML學習教程| jQuery入門知識| AJAX入門| Dreamweaver教程| Fireworks入門知識| SEO技巧| SEO優化集錦|
Copyright © DIV+CSS佈局教程網 All Rights Reserved