这应该可以解决问题:
将适用于输入和文本区域——无论您为每个设置设置什么默认值都将持续存在。按原样使用。
在此处查看小提琴:http: //jsfiddle.net/leifparker/DvqYU/2/
(这会将默认值提取并存储在数据属性中)
HTML
<textarea>I love bananas ..</textarea>
<textarea>How about you?</textarea>
<input type="text" value="Time for a bath ..">
<input type="text" value=".. because I smell">
JS
$('textarea, input[type=text]')
.each(function(){
$(this).data('defaultText', $(this).val());
})
.focus(function(){
if ($(this).val()==$(this).data('defaultText')) $(this).val('');
})
.blur(function(){
if ($(this).val()=='') $(this).val($(this).data('defaultText'));
});
编辑:
下面是 ANeves 提出的一个替代方案,它利用了 HTML5占位符属性。如果您不关心旧浏览器,您可以单独使用占位符HTML(它可以在本地工作,结果类似于上面的 JS),否则,如下所示,您需要添加一个 JS 后备。
在这里小提琴:http: //jsfiddle.net/leifparker/DvqYU/14/
HTML
<textarea placeholder="A few words about yourself"></textarea>
<textarea placeholder=".. and a few more about your mangy cat."></textarea>
<input type="text" placeholder="Your Awesome City">
<input type="email" placeholder="rickastin@youjustgot.com">
JS
function hasPlaceholderSupport() {
var input = document.createElement('input');
return ('placeholder' in input);
}
if (!hasPlaceholderSupport()){
$('textarea, input[type=text], input[type=email]')
.each(function(){
if ($(this).val()=='') $(this).val($(this).attr('placeholder'));
})
.focus(function(){
if ($(this).val()==$(this).attr('placeholder')) $(this).val('');
})
.blur(function(){
if ($(this).val()=='') $(this).val($(this).attr('placeholder'));
});
}