DIV CSS 佈局教程網

自製 jQuery placeholder 插件:為舊版 IE 補上輸入框提示文字
編輯:JQuery特效代碼     

HTML5 為文字輸入框帶來的 placeholder 屬性極為好用,但 IE 直到 IE9 都不支援。在還需要照顧舊版瀏覽器的年代,這意味著你得自己打造一個替代方案。以下是一個採「漸進增強」思路的 jQuery 插件:支援原生 placeholder 的瀏覽器完全不處理,只有不支援的才注入替代元素。

設計目標

  1. 外觀與行為盡量貼近原生 placeholder。
  2. 漸進增強——原生支援者不做任何事,避免多餘的 DOM 與事件。

一、工具方法

// 1. 偵測瀏覽器是否支援某元素的某屬性
var supportProperty = function (nodeType, property) {
    switch (arguments.length) {
        case 0: return false;
        case 1:
            var property = nodeType, nodeType = 'div';
            property = property.split('.');
            if (property.length == 1) {
                return typeof eles[nodeType][property[0]] !== 'undefined';
            } else if (property.length == 2) {
                return typeof eles[nodeType][property[0]][property[1]] !== 'undefined';
            }
        case 2:
            property = property.split('.');
            if (property.length == 1) {
                return typeof eles[nodeType][property[0]] !== 'undefined';
            } else if (property.length == 2) {
                return typeof eles[nodeType][property[0]][property[1]] !== 'undefined';
            }
            return false;
        default: return false;
    }
};

// 2. 取得元素在文件中的絕對位置
var getPositionInDoc = function (target, parent) {
    if (!target) { return null; }
    var left = 0, top = 0;
    do {
        left += target.offsetLeft || 0;
        top  += target.offsetTop  || 0;
        target = target.offsetParent;
        if (parent && target == parent) { break; }
    } while (target);
    return { left: left, top: top };
};

// 3. 快速建立 DOM 元素
var $c = function (tagName, id, className) {
    var ele = null;
    if (!eles[tagName]) {
        ele = eles[tagName] = document.createElement(tagName);
    } else {
        ele = eles[tagName].cloneNode(true);
    }
    if (id)        { ele.id = id; }
    if (className) { ele.className = className; }
    return ele;
};

getPositionInDoc 靠的是 offsetParent 鏈逐層累加。這是 jQuery 出現之前定位浮層的標準手法,理解它有助於明白瀏覽器的定位模型:offsetLeft/offsetTop 永遠相對於 offsetParent,所以要得到文件座標就必須一路往上加。今天的替代方案是 getBoundingClientRect() 加上 scrollX/scrollY,程式碼短得多。

二、主體:CustomPlaceholder 物件

每個需要補 placeholder 的輸入框,對應一個 CustomPlaceholder 實例,負責維護位置、提示文字、以及相關事件。

var CustomPlaceholder = function (box, input, option) {
    var self = this;
    var position = getPositionInDoc(input);

    self.input = input;
    self.option = { xOffset: 0, yOffset: 0 };
    for (var item in option) { self.option[item] = option[item]; }

    self.hint = self.createHintLabel(input.getAttribute('placeholder'), position);
    box.appendChild(self.hint);

    self.initEvents = function () {
        // 點擊提示文字時,把焦點交回輸入框
        $(self.hint).bind('click', function (e) {
            self.input.focus();
        });

        // 輸入框取得焦點,隱藏提示
        $(self.input).bind('focus', function (e) {
            self.hint.style.display = 'none';
        });

        // 輸入框失去焦點且為空,顯示提示
        $(self.input).bind('blur', function (e) {
            if (this.value == '') {
                self.hint.style.display = 'inline';
            }
        });
    };
    self.initEvents();
};

CustomPlaceholder.prototype = {
    createHintLabel: function (text, position) {
        var hint = $c('label');
        hint.style.position = 'absolute';
        hint.style.left = position.left + this.option.xOffset + 'px';
        hint.style.top  = position.top  + this.option.yOffset + 'px';
        hint.style.zIndex = '9999';
        hint.innerHTML = text;
        return hint;
    },
    position: function () {
        var position = getPositionInDoc(this.input);
        this.hint.style.left = position.left + this.option.xOffset + 'px';
        this.hint.style.top  = position.top  + this.option.yOffset + 'px';
    }
};

這裡有兩個值得注意的地方。其一,提示文字用 <label> 而非 <span> 或 <div>,是為了讓螢幕閱讀器能把它當作標籤朗讀,這是原設計中相當用心的一筆。其二,原範例寫了 hint.style.cusor = 'text',拼字有誤(應為 cursor),實際上不會生效;若要讓滑鼠移入時形狀正常,應在樣式表中處理。

三、插件本體

$.fn.placeholder = function (option) {
    // 能力偵測:原生支援則直接退出
    if (supportProperty('input', 'placeholder')) { return; }

    var customPlaceholders = [];

    if (this.length > 0) {
        var box = $c('div', 'dk_placeholderfixed_box');
        for (var i = 0, len = this.length; i < len; i++) {
            var input = this[i];
            if ($(input).is(':visible')) {
                customPlaceholders.push(new CustomPlaceholder(box, input, option));
            }
        }
        document.body.appendChild(box);
    }

    // 視窗尺寸改變時重新定位
    $(window).bind('resize', function (e) {
        for (var i = 0, len = customPlaceholders.length; i < len; i++) {
            customPlaceholders[i].position();
        }
    });
};

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