如何在输入字段上设置空白默认文本,并在元素被激活时清除它。
在现代浏览器中,您可以设置一个字段的 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;
});
使用onFocus
和onBlur
事件可实现此功能,即:
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;
}
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);">
<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);
});
我找到了jQuery插件(http://www.jason-palmer.com/2008/08/jquery-plugin-form-field-default-value/)并使用它 :)
你可以使用这个插件(我是合作者)
https://github.com/tanin47/jquery.default_text
它克隆一个输入字段并将其放置在那里。您可以使用占位符属性。
例如:<input type="text" name="fname" placeholder="名字">
请参考http://www.w3schools.com/tags/att_input_placeholder.asp进行检查。
placeholder
作为类,并将默认文本放在title
属性中即可。https://github.com/justinbangerter/placeholder.js - jbangerter