如何在输入字段上设置空白默认文本并在元素处于活动状态时将其清除。
9 回答
在现代浏览器中,您可以placeholder
在字段上设置属性以设置其默认文本。
<input type="text" placeholder="Type some text" id="myField" />
但是,在较旧的浏览器中,您可以使用 JavaScript 来捕获焦点和模糊事件:
var addEvent = function(elem, type, fn) { // Simple utility for cross-browser event handling
if (elem.addEventListener) elem.addEventListener(type, fn, false);
else if (elem.attachEvent) elem.attachEvent('on' + type, fn);
},
textField = document.getElementById('myField'),
placeholder = 'Type some text'; // The placeholder text
addEvent(textField, 'focus', function() {
if (this.value === placeholder) this.value = '';
});
addEvent(textField, 'blur', function() {
if (this.value === '') this.value = placeholder;
});
演示:http: //jsbin.com/utecu
使用onFocus
andonBlur
事件可以实现这一点,即:
onfocus="if(this.value=='EGTEXT')this.value=''"
和
onblur="if(this.value=='')this.value='EGTEXT'"
完整示例如下:
<input name="example" type="text" id="example" size="50" value="EGTEXT" onfocus="if(this.value=='EGTEXT')this.value=''" onblur="if(this.value=='')this.value='EGTEXT'" />
或者干脆
<input name="example" type="text" id="example" value="Something" onfocus="value=''" />
一旦清除该框,这将不会回发默认文本,但也将允许用户清除该框并在自动完成脚本的情况下查看所有结果。
声明非活动和活动状态的样式:
.active {
color: black;
}
.inactive {
color: #909090;
}
添加 Javascript 来处理状态的变化:
function toggleText(el)
{
var v = el.value;
//Remove text to allow editing
if(v=="Default text") {
el.value = "";
el.className = "active";
}
else {
//Remove whitespace
if(v.indexOf(" ")!=-1) {
split = v.split(" ").join("");
v = split;
}
//Change to inactive state
if(v=="") {
el.value = "Default text";
el.className = "inactive";
}
}
}
添加您的输入框,设置默认值、inactive
类集和指向toggleText()
函数的 Javascript 处理程序(如果您愿意,可以使用事件侦听器来执行此操作)
<input type="text" value="Default text" class="inactive" onFocus="toggleText(this);" onBlur="toggleText(this);">
从可用性的角度来看,输入组件中的文本应仅保留用于用户输入目的。如果用户未触及,输入中可能的默认值应该是有效的。
如果占位符文本旨在提示如何填充输入,则最好将其放在输入附近,当输入已填充时也可以看到它。此外,在文本组件中使用占位符文本可能会导致问题,例如盲文设备。
如果使用占位符文本,无论可用性指南如何,都应该确保它以一种不显眼的方式完成,以便它可以在没有 javascript 或 js 关闭时与用户代理一起使用。
我找到了 jQuery 插件(http://www.jason-palmer.com/2008/08/jquery-plugin-form-field-default-value/)并使用它:)
我所做的是为现代浏览器放置一个占位符属性:
<input id='search' placeholder='Search' />
然后,我使用 JQuery 为旧版浏览器做了一个后备:
var placeholder = $('search').attr('placeholder');
//Set the value
$('search').val(placeholder);
//On focus (when user clicks into the input)
$('search').focus(function() {
if ($(this).val() == placeholder)
$(this).val('');
});
//If they focus out of the box (tab or click out)
$('search').blur(function() {
if ($(this).val() == '')
$(this).val(placeholder);
});
这对我有用。
你可以使用这个插件(我是合著者)
https://github.com/tanin47/jquery.default_text
它克隆一个输入字段并将其放在那里。
它适用于具有著名焦点问题的 IE、Firefox、Chrome 甚至 iPhone Safari。
这样您就不必担心在提交之前清除输入字段。
或者
如果您只想 HTML5,您可以在输入字段上使用属性“占位符”
您可以使用占位符属性。
np。<input type="text" name="fname" placeholder="First name">
检查http://www.w3schools.com/tags/att_input_placeholder.asp