【问题标题】:How do you have grayed out text in a textfield that dissapears when the user clicks on it如何在用户单击时消失的文本字段中的文本变灰
【发布时间】:2010-12-26 03:54:58
【问题描述】:
在 HTML 和 JS 中,如何制作一个显示为灰色的文本字段,告诉用户该字段的用途,当用户单击该字段时该字段消失?
例如,在 Firefox 中,右上角的搜索字段会在没有输入任何内容时显示它使用哪个搜索引擎,然后一旦您单击它就是一个空的文本字段,但如果您将其留空并从文本字段中移除焦点,那么变灰的文字又回来了。
这种行为有名称吗?另外,是否可以在不使用 js 的情况下在纯 css 中进行 on focus / on blur 事件?
【问题讨论】:
标签:
javascript
html
textbox
textfield
【解决方案1】:
您所指的效果通常称为占位符效果。在 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/
【解决方案2】:
此行为出现在我的 URL 缩短器网站上:http://relk.in
基本思路是当onfocus事件触发时,你修改textfield的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');
}