首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >焦点上的占位符删除

问焦点上的占位符删除
EN

Stack Overflow用户
提问于 2013-01-15 22:13:16
回答 7查看 7.5K关注 0票数 2

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

我需要在IE中有这个功能-化身也。

我想让占位符隐藏在焦点上!我发现的每种解决方法都会在输入第一个类型时隐藏占位符。

我无法自己解决这个问题,它需要简单地删除输入的占位符-焦点上的文本,但如果input-value为空,也可以恢复占位符-文本上的模糊。

我正试着把这件事付诸实施

代码语言:javascript
复制
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('');
    }
  })
});


});

这会将占位符的值更改为"(nothing)“,行为如我所愿,但在模糊状态下它无法恢复占位符的值,因为它现在的值是"(nothing)”

//更新

我的解决方案是:

代码语言: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);
     }
  });
    });
EN

回答 7

Stack Overflow用户

回答已采纳

发布于 2013-01-15 22:35:08

如果你不想使用placeholder,你可以使用下面的代码或者使用这个简单的jQuery插件:

。

HTML

代码语言:javascript
复制
<input type='text' holder='First name'><br>
<input type='text' holder='Last name'><br>
<input type='text' holder='Age'>

JavaScript

代码语言: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。

票数 3
EN

Stack Overflow用户

发布于 2013-01-15 22:14:43

使用占位符属性:

代码语言:javascript
复制
<input type="text" placeholder="Search here">

对于不支持placeholder的浏览器,可以使用polyfill

票数 3
EN

Stack Overflow用户

发布于 2013-01-15 22:35:38

古老而不是最好的方法是:

代码语言:javascript
复制
<input type="text" name="fname" value="Enter text here" onFocus="if (this.value=='Enter text here'){this.value='';}"
onBlur="if (this.value==''){this.value='Enter text here';}" />

但它即使在IE6中也能正常工作。

票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/14339588

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档