在空输入字段中显示占位符文本
在onfocus
期间(在输入字段上)输入默认值如何被禁用,但在输入字段上可以写入任何类似默认值的字符不存在?在空输入字段中显示占位符文本
这里是简单的HTML =>
<input type="text" id="x">
和javascript =>
document.getElementById("x").onfocus = function(){
this.style.opacity = 0.5;
}
,但我不能做我想做的。
随着“HTML5”,新的功能和属性已经被引入用于形元素(如内置形式验证例如)
其中之一是placeholder
- 属性。它会在用户开始填充字段中的文本后,在空输入字段中显示指定的文本,这些字段将被隐藏。 的HTML的标记看起来是这样的:
<input type="text" name="first_name" placeholder="Fill in your name">
这个功能不是所有的浏览器都支持,但(你可以检查兼容性上caniuse.com
在你的代码,你可以检查一个简单的功能兼容性:
var placeHolderSupport = ('placeholder' in document.createElement('input'));
对于旧的浏览器,你需要编写一个备用的JavaScript - 功能,读取此属性和执行行为yourselve大约有一些这方面的博客,帖子在网络上,像一个从David Walsh,这可以帮助你。
编辑:
我偶然发现了这个gist由Hagenburger(according blog-post),应该实现你要实现对旧的浏览器太的行为。 注意:它是jQuery代码,不知道你是否使用它,但即使不是,它应该给你一个想法,该怎么做。
因此,考虑到兼容性 - 从上面检查:
if(!placeHolderSupport){
//gist code here (not sure if i'm allowed to copy this into my answer)
}
这样,本机占位符,实现在浏览器将被使用,如果它存在,否则,JavaScript的功能会照顾这个。
更新2012年9月11日
SO-用户和主持人ThiefMaster刚刚指出的马蒂亚斯Bynens,已经内置了检查placeholder
更好更新的jQuery的插件 - 支持。当然更好的办法来实现占位符,回退比我张贴的要点:
好吧把... i ++; – 2012-07-10 21:27:02
<input type="text" value="blah" name="Email"
id="Email" onblur="this.value = 'blah';"
onfocus="this.value = 'blah';" />
<input type="text" data-placeholder="Name" />
$(function(){
$('input').each(function(){
if($(this).val() == ''){
$(this).val($(this).data('placeholder'));
}
});
});
$('input').focusin(function(){
if($(this).val() == $(this).data('placeholder')){
$(this).val('');
}
}).focusout(function(){
if($(this).val().length < 0){
$(this).val($(this).data('placeholder'));
}
});
见例如快速和肮脏example here。
http://whathaveyoutried.com/ – Amaerth 2012-07-10 21:18:22
我已经尝试了很多,你知道,只是不写,因为它确实非常简单,但无法解决它。我会更新我的问题,并请帮助,如果你可以 – tnanoba 2012-07-10 21:20:08