【问题标题】:Getting placeholder to disappear/appear and positioning the cursor in front让占位符消失/出现并将光标定位在前面
【发布时间】:2011-06-14 04:28:54
【问题描述】:

我是 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'));
    }
});

谁能帮我解释一下?

【问题讨论】:

    标签: javascript jquery forms html


    【解决方案1】:
    <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/

    【讨论】:

      【解决方案2】:

      编辑 - 在我看来,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');
      });
      

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

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

      【讨论】:

      • 错了。他们在文本框下方放置了带有文本的label。 Foursquare 使用了类似的技术。
      • 您应该将其添加为答案。我没有看他们是如何实现它的,但我猜测并在其他地方做了同样的事情。
      • 其实除了文字是标签,没有渲染到背景图之外,几乎是一样的。他们改变焦点和模糊的背景图像,但只是改变颜色。当检测到添加到字段以隐藏标签的输入时,它们还会添加另一个类。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-01-05
      • 2018-10-08
      • 1970-01-01
      • 1970-01-01
      • 2023-03-27
      • 1970-01-01
      • 2011-11-19
      相关资源
      最近更新 更多