首页 » 性感的程序员,水哥专栏 » HTML 5 Placeholder 特性的模拟实现

HTML 5 Placeholder 特性的模拟实现

网页表单文字输入框内容提示 这一特性在 HTML 5 中由 placeholder 属性来实现,但它依然没有标准化,IE 10 之前不支持,控制其样式的伪元素的命名、特性还不统一,让人用起来有些不爽……

其实 HTML 4 原生的 value 属性配合 JavaScript 就能很好实现这个特性 ——

//  Version:  0.2

$(document).ready(function () {
    function InputTips_Hide() {
        if (this.value != this.defaultValue) {
            this.select();
            return;
        }
        var $_This = $(this);
        this.value = '';
        this.focus();
        $_This.css('color', $_This.data('color'));

        if (Boolean( $_This.data('type') )) {
            this.type = $_This.data('type');
            $_This.data('type', '');
        }
    }
    function InputTips_Show() {
        if (this.value != '') return;

        var $_This = $(this);
        this.value = this.defaultValue;
        this.blur();
        $_This.css('color', 'gray');

        if (jQuery.inArray(this.type, [
            'password', 'number',
            'email', 'url'
        ]) != -1) {
            $_This.data('type', this.type);
            this.type = 'text';
        }
    }
    $('input').filter(function () {
        return jQuery.inArray(this.type, [
            'text', 'search',
            'password', 'number',
            'email', 'url'
        ]) != -1;
    }).each(function () {
        if (this.defaultValue == '') return;

        var $_This = $(this);
        $_This.data('color', $_This.css('color'))
            .css('color', 'gray')
            .focus(InputTips_Hide)
            .hover(InputTips_Hide, InputTips_Show)
            .blur(InputTips_Show);

        if (jQuery.inArray(this.type, ['text', 'search']) != -1)
            return;
        $_This.data('type', this.type);
        this.type = 'text';
    });
});

文本框的 valueplaceholder 属性都可填写任何字符(一般字符 和 HTML 实体表示),也就是说我们可以用 字体图标的字符 来替代原来的图片图标,抛弃复杂的堆叠式 DOM 结构,实现文本框提示内容实现的简化与统一。(详见我的下篇博文)