当用户点击文本框时,如何在文本框中添加灰色的文本并在用户开始输入时自动消失?

4
在HTML和JS中,如何制作一个文本框,其中包含灰色文本,告诉用户该字段的用途,并在用户单击该字段时消失?
例如,在Firefox中,右上角的搜索字段在未输入任何内容时会显示使用哪个搜索引擎,然后一旦单击它,它就是一个空文本字段,但如果您将其留空并从文本字段中移除焦点,则灰色文本会再次出现。
这种行为有名称吗?此外,是否可能仅使用纯CSS而不使用JS来执行on focus / on blur事件?
2个回答

6
您所指的效果通常称为占位符效果。在HTML5中,通过在输入标签中简单地添加新属性“placeholder”,可以在某些浏览器中实现此效果。例如...
 <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/

});


1

这是关于我的URL缩短网站的行为:http://relk.in

基本思路是当onfocus事件触发时,将文本字段的CSS修改为普通类,然后在onblur时,重新应用之前的类。

不过,你不能仅使用纯CSS实现这一点。

例如:

var textfield = document.getElementById('someTextField');
textfield.onfocus = function() {
   this.className = this.className.replace('oldClassName', 'newClassName');
};
textfield.onblur = function() {
   this.className = this.className.replace('newClassName', 'oldClassName');
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接