我的应用程序需要一个文本字段和一个文本区域字段的占位符。我知道Internet Explorer不支持占位符。我环顾四周,发现了一些后备代码,它们只对文本字段有效。我怎样才能让它在文本区域中也能工作。
代码:
jQuery(function() {
jQuery.support.placeholder = false;
test = document.createElement('input');
if('placeholder' in test) jQuery.support.placeholder = true;
});
$(function() {
if(!$.support.placeholder) {
var active = document.activeElement;
$('input[type=text], textarea').focus(function () {
if ($(this).attr('placeholder') != '' && $(this).val() == $(this).attr('placeholder')) {
$(this).val('').removeClass('hasPlaceholder');
}
}).blur(function () {
if ($(this).attr('placeholder') != '' && ($(this).val() == '' || $(this).val() == $(this).attr('placeholder'))) {
$(this).val($(this).attr('placeholder')).addClass('hasPlaceholder');
}
});
$('input[type="text"], textarea').blur();
$(active).focus();
$('form').submit(function () {
$(this).find('.hasPlaceholder').each(function() { $(this).val(''); });
});
}
});
HTML:
<li>
<input type="text" placeholder="To:" id="to" autocapitalize="off" autocorrect="off" autocomplete="off" />
</li>
<li>
<textarea placeholder="Message:" id="body" rows="10" cols="30" autocapitalize="off" autocorrect="off" autocomplete="off"></textarea>
</li>
发布于 2012-07-31 20:36:21
将$(':text')
更改为$('input[type="text"], textarea')
或者,这个现有的jQuery插件:
https://github.com/mathiasbynens/jquery-placeholder
适用于文本和多种类型的输入字段,包括密码字段
发布于 2013-06-10 12:16:31
<script type="text/javascript">
$(function() {
if(!$.support.placeholder) {
var active = document.activeElement;
$('input[type="text"], textarea').focus(function () {
if ($(this).attr('placeholder') != '' && $(this).val() == $(this).attr('placeholder')) {
$(this).val('').removeClass('hasPlaceholder');
}
}).blur(function () {
if ($(this).attr('placeholder') != '' && ($(this).val() == '' || $(this).val() == $(this).attr('placeholder'))) {
$(this).val($(this).attr('placeholder')).addClass('hasPlaceholder');
}
});
$('input[type="text"], textarea').blur();
$(active).focus();
$('form').submit(function () {
$(this).find('.hasPlaceholder').each(function() { $(this).val(''); });
});
}
});
</script>
发布于 2012-07-31 20:34:07
它正在使用text selector,请将其更改为也使用textarea。
$(':text')
应该是
$(':text, textarea')
$('input[type=text], textarea')
https://stackoverflow.com/questions/11748531
复制相似问题