用于管理占位符的Javascript插件

时间:2011-09-06 18:59:39

标签: javascript jquery

查看https://twitter.com/signup

上的Twitter注册页面

即使您点击第一个输入字段“全名”占位符一直停留在那里,直到我开始输入内容。太棒了。

有没有人知道一个好的jQuery插件接近它?

3 个答案:

答案 0 :(得分:0)

这里有很多插件。这是我使用的本土解决方案:

/**
 *  Yet another textbox hint plugin...
 *  Usage: $('.selector').hint();
 *  The title attribute of the input will be used as the watermark value.
 */
(function($) {
    $.fn.hint = function() {
        var hintedClass = 'hinted';
        return this.each(function() {
            var $field = $(this),
                title = $field.attr('title'),
                $form = $(this.form);

            // bail out if there isn't a title attribute
            if (!title) { return; }

            // add/remove hint behavior
            var addHint = function() {
                    $field.val() || $field.addClass(hintedClass).val(title);
                },
                removeHint = function() {
                    if ($field.hasClass(hintedClass) && $field.val() === title) {
                        $field.val('').removeClass(hintedClass);
                    }
                };

            // set our focus/blur handlers
            $field.focus(removeHint).blur(addHint);

            // if the field isn't already focused, add the hint now
            $field.is(':focus') || addHint();

            // form submission handling
            $form.submit(removeHint);
        });
    };
})(jQuery);

答案 1 :(得分:0)

支持HTML5 placeholder attribute

的浏览器需要零JavaScript
<label>Description: <input type="text" name="desc" placeholder="My Email Account"></label>

答案 2 :(得分:0)

我编写的this example功能就像twitter一样,但如果你想要精确的样式,你可能想从twitter bootstrap CSS中获取一些额外的CSS。

我在这个类似的stackoverflow question中详细讨论了这个方法。