javascript - 占位符删除焦点

标签 javascript jquery html attributes placeholder

我使用的是“占位符”属性。用于输入字段中的占位符文本

我也需要在 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/

相关文章:

javascript - 如何获取文本 block 中的字符坐标?

javascript - 带有 CSS3 过渡的 jQuery 方向感知悬停

html - 如何减少 Bootstrap 4 列表组中的间距

javascript - Angular 变量未更新

javascript - 使用 AngularJS 从数组中提取特定记录

javascript - 单击行时表的高度发生变化

javascript - 针对鼠标悬停更改内容的细化 jquery 文件

javascript - FadeIn//FadeOut 一些引用

python - 如何使用 BeautifulSoup 查找没有 id 或类名的 html 标签?

javascript - Webpack 不注入(inject)变量