问题描述
我总是在工作中使用此代码段:
I always use this snippet in my work:
<input type="text" onblur="if (this.value=='') { this.value='your email'; }" onfocus="if (this.value == 'your email') { this.value=''; }" value="your email" />
基本上,它将显示一个带有您的电子邮件"作为值的文本框,当单击文本输入框时-该值将变为空白..因此,他们键入电子邮件..如果他们不键入电子邮件,它将重设回您的电子邮件".
Basically it will show a text box with "your email" as the value, when the clicks the text input box - the value becomes blank.. thus they type their email.. if they don't type an email it will reset back to the "your email".
我想对textarea执行此操作或类似操作并将其转换为jQuery(也是jQuery中的上述代码)?
I want to do this or similar with textarea and convert it to jQuery (also the above code in jQuery)?
<textarea name="msg">Message:</textarea><br />
推荐答案
这应该可以解决问题:
对于输入法和文本区域都将起作用-不管您为它们设置的默认值如何,都将保持不变.按原样使用.
Will work for both inputs and textareas -- Whatever default you set for each will persist. Use as is.
在此处查看小提琴: http://jsfiddle.net/leifparker/DvqYU/2/
(这会将默认值提取并存储在data属性中)
(This pulls and stores the default value in a data attribute)
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的 placeholder 属性.如果您不关心旧的浏览器,则可以单独使用 placeholder HTML(它本身可以运行,其结果类似于上面的JS),否则,如下所示需要添加一个JS后备广告.
An alternative brought up by ANeves, and which makes use of the HTML5 placeholder attribute is below. If you don't care about old browsers, you can use the placeholder HTML on its own (and it works natively, with results similar to the JS above), or otherwise, as below, you'll need to add a JS fallback.
在这里拨弄: 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="[email protected]">
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'));
});
}
这篇关于我可以使用jquery来空白textarea字段或ajax之类的输入框吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!