我使用的是“占位符”属性。用于输入字段中的占位符文本
我也需要在 IE 版本中拥有此功能。
我希望占位符隐藏在 FOCUS 上!我发现的每个解决方法都会在输入第一种类型时隐藏占位符。
我自己无法解决,它需要简单地删除输入的焦点占位符文本,但如果输入值为空,也可以恢复模糊的占位符文本。
我正在努力让它发挥作用
jQuery(document).ready(function () {
jQuery('[placeholder]').focus(function() {
input = jQuery(this);
if (input.val() == input.attr('placeholder')) {
input.val('');
input.removeClass('placeholder');
input.attr('placeholder','')
}
}).blur(function() {
var input = jQuery(this);
if (input.val() == '' || input.val() == input.attr('placeholder')) {
input.addClass('placeholder');
input.val(input.attr('placeholder'));
}
}).blur().parents('form').submit(function() {
jQuery(this).find('[placeholder]').each(function() {
var input = jQuery(this);
if (input.val() == input.attr('placeholder')) {
input.val('');
}
})
});
});
这会将占位符的值更改为“(无)”并且行为如我所愿,但在模糊时它无法恢复占位符值,因为它现在是“(无)”
//更新
我的解决方案:
$(function()
{
$('input').each(function()
{
$(this).val($(this).attr('holder'));
});
$('input').focus(function()
{
if($(this).attr('holder')==$(this).val())
{
$(this).val('');
}
});
$('input').focusout(function()
{
if($.trim($(this).val())=='')
{
var holder = $(this).attr('holder');
$(this).val(holder);
}
});
});
最佳答案
如果您不想使用placeholder
,您可以使用下面的代码或使用这个简单的jQuery 插件:
jQuery Placeholder .
jsFiddle Live Demo Of Code Below
HTML
<input type='text' holder='First name'><br>
<input type='text' holder='Last name'><br>
<input type='text' holder='Age'>
JavaScript
$(function() {
$('input').each(function() {
$(this).val($(this).attr('holder'));
});
$('input').focus(function() {
if($(this).attr('holder')==$(this).val()) {
$(this).val('');
}
});
$('input').focusout(function() {
if($.trim($(this).val())=='') {
var holder = $(this).attr('holder');
$(this).val(holder);
}
});
});
您也可以使用这个简单的 jQuery 插件:jQuery Placeholder .
关于javascript - 占位符删除焦点,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14339588/