跨浏览器支持Placeholder

一、什么是 Placeholder ?

在 HTML5 的 input 标签中新增了一个 placeholder 属性,作用是在输入框中默认显示一些提示文字,以创造更好的用户体验。

使用方法:

<input type="text" placeholder="Username" />

查看 Demo

该特性仅被现代浏览器支持,在旧版 IE 下我们可以使用 javascript 来模拟实现。

二、Placeholder 的 js 实现

var doc = document,
inputs = doc.getElementsByTagName('input'),
 
// 检测 placeholder 支持
supportPlaceholder = 'placeholder' in doc.createElement('input'),
 
/*
 * 创建 placeholder
 * @param {ELEMENT} input 传入的 input 对象
 * @return {VOID}
 * @author: sofish Lin http://sofish.de
 */
placeholder = function (input) {
    var text = input.getAttribute('placeholder'),
        defaultValue = input.defaultValue;
 
    // 制作一个假 placeholder
    // 需要 css 配合,在 JS 中设置 style 并不太好
    input.value = text;
 
    // 聚焦去掉假 placeholder
    input.onfocus = function () {
        if (input.value === defaultValue || input.value === text) {
            this.value = '';
        }
    }
 
    // 当失焦值为空时,补回 placeholder 的值
    input.onblur = function () {
        if (input.value === '') {
            this.value = text;
        }
    }
};
 
if (!supportPlaceholder) {
    for (var i = 0, len = inputs.length; i < len; i++) {
        var input = inputs[i],
            text = input.getAttribute('placeholder');
 
        // 当 input[type=text] 并且 placeholder 值不为空是执行
        if (input.type === 'text' && text) {
            placeholder(input);
        }
    }
}

三、Placeholder 的 jQuery 插件

为了让代码可以重用,而不必为页面中每个 <input> 都写上相应的处理逻辑,有人专门写了一个 jQuery 下的插件。于是我们只需在页面引用一段 js ,就可以像 HTML5 的标准写法一样,在 input 中添加属性 placeholder 来实现这个效果了,简洁高效。同时,在 HTML5 时代真正来临时(也就是所有主流浏览器都开始支持 HTML5 的时候),直接移除这个插件的 js 引用即可,无需做任何重构。

插件主页:
http://webcloud.se/code/jQuery-Placeholder/

题外话:工作以后,每天都在赶项目进度,没有时间思考和学习了,直到今天圣诞节长假才有空更新博客。不管怎样,一定要坚持每天看完 GR 订阅,坚持解决重大架构问题要写 Blog 记笔记。各位还身处校园的同学,好好珍惜自由的时间吧,那是你可以自主把握的,让它更有价值和意义。