让占位符消失/出现并将光标定位在前面

时间:2011-06-13 19:53:49

标签: javascript jquery forms html5

我是JavaScript,jQuery以及其他所有内容的初学者,所以当我看到HTML5支持占位符时,我很满意。也就是说,直到我想要增强其行为。我想要做的是把我在this post中学到的东西(特别是corresponding jsFiddle),但修改它,以便:

  • 当关注输入字段时,光标会自动以您看不到的方式移动到占位符的开头。
  • 当我在输入字段中开始输入(不是经过一段时间)后,占位符消失了(如果我删除了我在输入字段中输入的内容,它会然后重新出现

我看到时髦的实现正是我正在做的事情(特别是来自Tubmlr和Square的主页,以及Foursquare的“加入”页面),我希望自己找到如何做到这一点。

上述jsFiddle的代码,我想修改/增强:

$('.placeholder').each(function(){
    $(this).data('placeholder', $(this).attr('data-title'));
    $(this).val($(this).attr('data-title'));
});

$('.placeholder').live('keydown', function(){
    if ($(this).val() == $(this).data('placeholder')) {
        $(this).val('');         
    }
});

$('.placeholder').live('blur', function(){
    if ($(this).val().trim() == '') {
        $(this).val($(this).data('placeholder'));
    }
});

有人可以帮我解释一下吗?

2 个答案:

答案 0 :(得分:0)

编辑 - 在我看来,Tumblr正在设置一个背景图像,其中包含文本(注意文字不可选)。因此,只需在输入焦点时将背景图像放入输入中,然后在模糊时将其移除。这不是他们如何做到的,因为js1568指出。也就是说,这就是我在其他地方实施的方式。引用的标签方法看起来也更简单,更直接。

$(your input selector here).focus(function(){
  $(this).css('background-image', 'url(background image with text in it.png)');
});

$(your input selector here).blur(function(){
  $(this).css('background-image', 'url(background image in different color with text in it.png');
});

当用户开始输入时,他们会更改背景图像,因此您需要在输入时检查输入值是否为空 - 如果不是,请删除背景图像:< / p>

$(your input selector here).keypress(function(){
  if ($(this).val() != "") {
    $(this).css('background-image', '');
  }
});

答案 1 :(得分:0)

<style>
form div { 
 position:relative; 
}
div label { 
  position:absolute;
  top:0;
  left:0;
  color:#666;
}
div input {
  background: transparent;
}
</style>
...
<script>
$(document).ready(function() {
  $('input').keyup(function() {
    if ($(this).val().length) {
      $('label[for='+$(this).attr('name')+']').fadeOut();
    } else {
      $('label[for='+$(this).attr('name')+']').fadeIn();
    }
  });
});
</script>
...
<form>
<div>
<label for="name">Name</label>
<input id="name" name="name" />
</div>
</form>

http://jsfiddle.net/Pbn5K/4/

相关问题