【问题标题】:Alter existing jQuery to make span placeholder更改现有的 jQuery 以制作 span 占位符
【发布时间】:2011-11-29 15:52:57
【问题描述】:

只要我的<label for="">input 名称和ID 匹配,我就有一些提供占位符的jQuery。然而,事实并非如此,所以我决定只使用<span> 作为占位符。有人可以帮助更改我的 jQuery 以使我正在使用的 <span> 类“持有人”工作吗?目标是让占位符保持焦点,在输入存在时消失,然后在输入消失时重新出现。

这是我正在使用的 HTML:

<div id="placeholder">
  <span class="holder">This is the placeholder...</span>
  <%= f.text_area :body, :id =>"Placeholder" %>
</div>

还有我目前的 jQuery:

$(document).ready(function() {
    $('textarea').keyup(function() {
        if ($(this).val().length) {
            $('label[for="' + $(this).attr('name') + '"]').hide();
        } else {
            $('label[for="' + $(this).attr('name') + '"]').show();
        }
    });
});

谢谢!

【问题讨论】:

    标签: jquery placeholder


    【解决方案1】:

    您希望绑定到focusblur 事件并将&lt;span&gt; 绝对定位在&lt;textarea&gt; 之上。从一些 CSS 开始:

    #placeholder {
        position: relative;
    }
    
    .holder {
        position: absolute;
        top: 2px;
        left: 2px;
        display: none;
    }
    

    然后是 jQuery:

    $('.holder').click(function() {
        $(this).siblings('textarea').focus();
    });
    $('#Placeholder').focus(function() {
        $(this).siblings('.holder').hide();
    });
    $('#Placeholder').blur(function() {
        var $this = $(this);
        if($this.val().length == 0)
            $(this).siblings('.holder').show();
    });
    $('#Placeholder').blur();
    

    最后的$('#Placeholder').blur() 调用用于初始化&lt;span&gt; 的状态,这样如果&lt;textarea&gt; 以内容开头,它将处于正确的状态。

    还有一个快速演示:http://jsfiddle.net/ambiguous/PLrf3/1/

    顺便说一句,在同一页面中包含 id="placeholder"id="Placeholder" 可能会导致一些混乱。您最好为您的id 属性选择一个标准方案(camelCasewords-and-hyphens 或其他)并坚持下去。只是大小写不同可能会造成混淆,并且可能看起来像是一个错字。

    【讨论】:

      【解决方案2】:

      这样的事情应该可以工作:

      $(function() {
          $("span.holder + textarea").keyup(function() {
              if($(this).val().length) {
                  $(this).prev('span.holder').hide();
              } else {
                  $(this).prev('span.holder').show();
              }
          });        
      });
      

      这应该适用于页面上的所有文本区域,如果它们前面有 span.holder

      【讨论】:

        猜你喜欢
        • 2015-05-07
        • 2013-07-01
        • 2012-03-03
        • 2013-02-04
        • 2011-07-11
        • 1970-01-01
        • 1970-01-01
        • 2022-12-06
        相关资源
        最近更新 更多