如何使HTML文本框为空时显示提示?

时间:2020-03-06 14:29:04  来源:igfitidea点击:

我希望网页上的搜索框以灰色斜体显示单词" Search"。当框获得焦点时,它应该看起来像一个空的文本框。如果其中已经有文本,则应正常显示文本(黑色,非斜体)。这我通过除去标签来避免混乱。

顺便说一句,这是页面上的Ajax搜索,因此没有按钮。

解决方案

我们可以添加和删除特殊的CSS类,并使用JavaScript修改输入值onfocus/onblur

<input type="text" class="hint" value="Search..."
    onfocus="if (this.className=='hint') { this.className = ''; this.value = ''; }"
    onblur="if (this.value == '') { this.className = 'hint'; this.value = 'Search...'; }">

然后使用我们想要的CSS样式指定一个提示类,例如:

input.hint {
    color: grey;
}

我们可以轻松地将一个框显示为"搜索",然后将焦点更改为它时,将文本删除。像这样的东西:

&lt;input onfocus =" this.value =''" type =" text" value =" Search" />

当然,如果我们这样做,则用户自己的文本在单击时会消失。因此,我们可能想使用更强大的功能:

<input name="keyword_" type="text" size="25"  style="color:#999;" maxlength="128" id="keyword_"
onblur="this.value = this.value || this.defaultValue; this.style.color = '#999';"
onfocus="this.value=''; this.style.color = '#000';"
value="Search Term">

最好的方法是使用jQuery或者YUI之类的JavaScript库连接JavaScript事件,并将代码放入外部.js文件中。

但是,如果我们想要一个快速而又肮脏的解决方案,这就是内联HTML解决方案:

<input type="text" id="textbox" value="Search"
    onclick="if(this.value=='Search'){this.value=''; this.style.color='#000'}" 
    onblur="if(this.value==''){this.value='Search'; this.style.color='#555'}" />

更新:添加了所需的着色材料。

使用背景图像渲染文本:

input.foo { }
 input.fooempty { background-image: url("blah.png"); }

然后,我们要做的就是检测"值== 0"并应用正确的类:

<input class="foo fooempty" value="" type="text" name="bar" />

jQuery JavaScript代码如下所示:

jQuery(function($)
{
    var target = $("input.foo");
    target.bind("change", function()
    {
        if( target.val().length > 1 )
        {
            target.addClass("fooempty");
        }
        else
        {
            target.removeClass("fooempty");
        }
    });
});

我们想为onfocus分配这样的内容:

if (this.value == this.defaultValue)
    this.value = ''
this.className = ''

和这个模糊:

if (this.value == '')
    this.value = this.defaultValue
this.className = 'placeholder'

(如果需要,我们可以使用一些更聪明的东西(例如框架函数)来进行类名切换。)

使用这样的CSS:

input.placeholder{
    color: gray;
    font-style: italic;
}

这就是所谓的文本框水印,它是通过JavaScript完成的。

  • http://naspinski.net/post/Text-Input-Watermarks-using-Javascript-(IE-Compatible).aspx

或者,如果我们使用jQuery,则更好的方法是:

  • http://digitalbush.com/projects/watermark-input-plugin/
  • 或者code.google.com/p/jquery-watermark

首次加载页面时,将在文本框中显示"搜索",如果需要,将其显示为灰色。

当输入框获得焦点时,请选择搜索框中的所有文本,以便用户可以开始输入内容,这将在此过程中删除所选的文本。如果用户想再次使用搜索框,这也将很好地工作,因为他们不必手动突出显示以前的文本即可将其删除。

<input type="text" value="Search" onfocus="this.select();" />

这是一个带有Google Ajax库缓存和jQuery魔术的功能示例。

这将是CSS:

<style type="text/stylesheet" media="screen">
    .inputblank { color:gray; }  /* Class to use for blank input */
</style>

这将是JavaScript代码:

<script language="javascript"
        type="text/javascript"
        src="http://www.google.com/jsapi">
</script>
<script>
    // Load jQuery
    google.load("jquery", "1");

    google.setOnLoadCallback(function() {
        $("#search_form")
            .submit(function() {
                alert("Submitted. Value= " + $("input:first").val());
                return false;
        });

        $("#keywords")
            .focus(function() {
                if ($(this).val() == 'Search') {
                    $(this)
                    .removeClass('inputblank')
                    .val('');
                }
            })
            .blur(function() {
                if ($(this).val() == '') {
                    $(this)
                    .addClass('inputblank')
                    .val('Search');
                }
            });
    });
</script>

这就是HTML:

<form id="search_form">
    <fieldset>
        <legend>Search the site</legend>
            <label for="keywords">Keywords:</label>
        <input id="keywords" type="text" class="inputblank" value="Search"/>
    </fieldset>
</form>

我希望这足以使我们对GAJAXLib和jQuery都感兴趣。

来自http://asp.net的用户AJAXToolkit

对于jQuery用户:naspinski的jQuery链接似乎已损坏,但是请尝试以下操作:
http://remysharp.com/2007/01/25/jquery-tutorial-text-box-hints/

我们可以获得免费的jQuery插件教程作为奖励。 :)

$('input[value="text"]').focus(function(){ 
if ($(this).attr('class')=='hint') 
{ 
   $(this).removeClass('hint'); 
   $(this).val(''); 
}
});

$('input[value="text"]').blur(function(){
  if($(this).val() == '')
  {
    $(this).addClass('hint');
    $(this).val($(this).attr('title'));
  } 
});

<input type="text" value="" title="Default Watermark Text">

这称为"水印"。

我发现了jQuery插件jQuery水印,它与第一个答案不同,不需要额外的设置(原始答案在提交表单之前也需要进行特殊调用)。

我发现jQuery插件jQuery Watermark优于顶部答案中列出的插件。为什么更好?因为它支持密码输入字段。同样,设置水印(或者其他属性)的颜色就像在CSS文件中创建.watermark引用一样容易。

我前一段时间在我的网站上发布了一个解决方案。要使用它,请导入单个.js文件:

<script type="text/javascript" src="/hint-textbox.js"></script>

然后使用CSS类hintTextbox注释我们想要提示的任何输入:

<input type="text" name="email" value="enter email" class="hintTextbox" />

此处提供更多信息和示例。

我们可以使用HTML(浏览器支持)中的placeholder属性来设置占位符。可以使用CSS来更改"字体样式"和"颜色"(尽管对浏览器的支持是有限的)。

input[type=search]::-webkit-input-placeholder { /* Safari, Chrome(, Opera?) */
 color:gray;
 font-style:italic;
}
input[type=search]:-moz-placeholder { /* Firefox 18- */
 color:gray;
 font-style:italic;
}
input[type=search]::-moz-placeholder { /* Firefox 19+ */
 color:gray;
 font-style:italic;
}
input[type=search]:-ms-input-placeholder { /* IE (10+?) */
 color:gray;
 font-style:italic;
}
<input placeholder="Search" type="search" name="q">

使用jQuery Form Notifier,它是最受欢迎的jQuery插件之一,并且不会受到此处其他jQuery建议所做的错误的影响(例如,我们可以自由设置水印的样式,而不必担心它是否会保存到数据库中) )。

jQuery Watermark直接在表单元素上使用单个CSS样式(我注意到,应用于水印的CSS字体大小属性也影响了文本框,而不是我想要的)。 jQuery Watermark的优点是我们可以将文本拖放到字段中(jQuery Form Notifier不允许这样做)。

其他人建议的另一个(digitalbrush.com上的一个)会不小心将水印值提交到表单中,因此我强烈建议我们反对。

如果我们很高兴只对较新的浏览器拥有此功能,那么另一个选择是使用HTML 5的placeholder属性提供的支持:

<input name="email" placeholder="Email Address">

在没有任何样式的情况下,Chrome中的外观如下:

我们可以在此处以及使用CSS的HTML5占位符样式中进行演示。

确保检查此功能的浏览器兼容性。 3.7中添加了对Firefox的支持。铬很好。 InternetExplorer仅在10中添加了支持。如果定位的浏览器不支持输入占位符,则可以使用名为jQuery HTML5 Placeholder的jQuery插件,然后只需添加以下JavaScript代码即可启用它。

$('input[placeholder], textarea[placeholder]').placeholder();