javascript - 您如何使文本字段中的文本变灰,当用户单击它时该文本会消失

标签 javascript html textbox textfield

在 HTML 和 JS 中,如何制作一个文本字段,该文本字段的文本显示为灰色,告诉用户该字段的用途,当用户单击该字段时该文本字段会消失?

例如,在 Firefox 中,右上角的搜索字段说明了当没有输入任何内容时它使用的搜索引擎,然后一旦你点击它是一个空的文本字段,但如果你将它留空并从文本字段中移除焦点然后变灰的文本又回来了。

这个行为有名字吗?另外,是否可以在不使用 js 的情况下在纯 css 中执行聚焦/模糊事件?

最佳答案

您所指的效果通常称为占位符效果。在 HTML5 中,这种效果在某些浏览器中是可能的,只需在您的输入标签中放置新属性“占位符”。比如……

 <input type='text' placeholder='Place Holder Text'/>
 <input type='text'/> <!-- Example with no title-->
 <input type='text' title='Your title'/>

这也可以在 JavaScript 中使用 CSS 来完成,方法是为事件类设置样式并切换事件样式以及项目的标题标签。比如……

$(document).ready(function(){
// Select all input fields. (You will probably want to filter this down even further).
var inputs = $('input[type=text]');

// Set all the inputs to the title value.
inputs.each(function(){
    $(this).val($(this).attr('title')).addClass('unfocused'); // Styling Class for inputs.
});

// When the user focuses on an input
inputs.focus(function(){
    var input = $(this);
    if(input.val() == input.attr('title')){
        $(this).removeClass('unfocused').val('');
    }
});
// When the user loses focus on an input    
inputs.blur(function(){
    var input = $(this);
    if(input.val() == ''){ // User has not placed text
        input.val(input.attr('title')).addClass('unfocused');
    }
}); 

});

测试的功能可以在这里看到:http://www.jsfiddle.net/F8ZCW/5/

关于javascript - 您如何使文本字段中的文本变灰,当用户单击它时该文本会消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4532686/

相关文章:

ms-access - Access 报告 "Can Grow"属性需要影响相邻控件

javascript - 我的 JSON HTTP 请求出现问题

javascript - # url 部分隐藏和显示

javascript - document.getElementById() 在 IE9 上返回 null

jquery - 通过jQuery隐藏div

html - 使用 SED/AWK/GREP 从 html 中提取 href/url

html - 使用 xpathSApply 的相同代码搜索多个路径

javascript - 在javascript中接受IP的文本框验证

javascript - 拉斐尔·Javascript

C# Windows 窗体 - 从局部变量分配文本框值(数字)