【发布时间】:2013-09-28 14:45:02
【问题描述】:
所以,我试图让占位符属性在 IE9 及更低版本中工作。但是,我的行为很奇怪(请参见下面的屏幕截图)。
找到this website,决定使用下面的JS代码:
JS:
// Checks browser support for the placeholder attribute
jQuery(function() {
jQuery.support.placeholder = false;
test = document.createElement('input');
if('placeholder' in test) jQuery.support.placeholder = true;
});
// Placeholder for IE
$(function () {
if(!$.support.placeholder) {
var active = document.activeElement;
$(':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');
}
});
$(':text, textarea').blur();
$(active).focus();
$('form').submit(function () {
$(this).find('.hasPlaceholder').each(function() { $(this).val(''); });
});
}
});
HTML:
<p>
<label>To: </label>
<input type="text" id="toEmail" placeholder="Recipient's Email Address" />
</p>
<p>
<label>From:</label>
<input type="text" id="fromName" placeholder="Your Name" />
</p>
<p>
<label>From: </label>
<input type="text" id="fromEmail" placeholder="Your Email Address" />
</p>
<p>
<label>Message:</label>
<textarea rows="5" cols="5" id="messageEmail"></textarea>
</p>
CSS:
.hasPlaceholder {
color: #999;
}
我的网站打开了一个带有表单的模式。但是,当第一次打开模式时,没有显示占位符文本:
但是,如果我单击文本字段,然后单击文本字段外,则会显示占位符文本。
我希望在打开模式后立即显示文本。真的是这样……
仅供参考-我怀疑文本最初可能没有出现,因为我的模式最初是隐藏的。如果是这种情况,我该如何解决?
注意:我知道存在插件。我不想使用插件。
【问题讨论】:
-
链
.blur()在.blur(function () {/* ... */})之后,还有,你为什么不缓存$(this)? -
@PaulS。恐怕没有用...
-
@PaulS。我想我可以,但我使用的是借来的代码,所以我对它做了很少的修改。如果通过缓存
this我可以存储变量并将其注入模态,那么我可以看到它的用处。 -
$(this).show( '.placeholder' ); //Not working照它说的做,但它不起作用。我不确定$(this)应该是什么,或者将类选择器传递给show应该做什么,但我无法按原样使用该行运行此代码。不确定此评论是否有帮助。 -
@lemieuxster 是的,那是糟糕的代码。我把它拿出来了。我会在这里拿出来。
标签: javascript html css internet-explorer placeholder