如何使用提示文本预填充输入文本字段,该提示文本在键入时消失(jQuery) [英] How to prepopulate input text fields with prompting text which disappears on typing (jQuery)

查看:93
本文介绍了如何使用提示文本预填充输入文本字段,该提示文本在键入时消失(jQuery)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当您单击Stack Overflow上的"Ask Question"按钮时,问题标题部分将预先填充浅灰色文本,显示为

When you click on the "Ask Question" button on Stack Overflow, the question title section is prepopulated with light gray text that reads

"what's your programming question? be specific"

然后,当您在标题"字段中单击并开始键入内容时,该文本就会消失.

Then when you click inside the Title field and start typing, that text disappears.

我想在我的应用程序中做同样的事情.

I want to do the same thing in my app.

jQuery是否有技巧来实现这一目标?

Is there a trick in jQuery to accomplish that?

具体地说,当有人开始输入文字时,如何将占位符文本的颜色从浅灰色更改为默认文本颜色?

推荐答案

最简单的方法是使用html(尽管是html5)的placeholder属性:

The easiest way to achieve this is with html (albeit html5)'s placeholder attribute:

<input type="text" placeholder="Enter email address." name="email" />

它将显示为浅色"文本,当用户开始输入内容时消失.

It will appear as "lighter colored" text that disappears when the user starts entering something.

但是,如果您真的想/需要使用jQuery(因为上述html解决方案仅在更现代/兼容的浏览器中可用),请采用以下方法:

However, if you really want/need to use jQuery (as the above html-solution is only usable in the more modern/compliant browsers), here's a way:

$(document).ready(
    function(){
        $('input:text').each(
            function(){
                $(this).click(
                    function(){
                        $(this).val('');
                    });
                $(this).blur(
                    function(){
                        if ($(this).val == '') {
                            $(this).val($(this).attr('placeholder'));
                        }
                    });
            });
    });


已编辑,以便在最终的if中添加缺少的),并且还添加了上述内容的略微修订版​​,并带有略显灰色的placeholder文字(因为我认为OP会例如,在下面的评论中给出他的问题):


Edited to add a missing ) in the final if, and also to add a slightly revised version of the above that features slightly greyed-out placeholder text (as I assume the OP would like, given his question in the comments, below):

$(document).ready(
    function(){
        $('input:text').each(
            function(){
                $(this)
                    .val($(this).attr('placeholder'))
                    .css('color','#999');
                $(this).click(
                    function(){
                        $(this)
                            .val('')
                            .css('color','#000');
                    });
                $(this).blur(
                    function(){
                        if ($(this).val() === ''){
                            $(this)
                                .val($(this).attr('placeholder'))
                                .css('color','#999');
                        }
                    });
            });
    });

JS小提琴演示.

这篇关于如何使用提示文本预填充输入文本字段,该提示文本在键入时消失(jQuery)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆