改变现有的jQuery来制作span占位符

时间:2011-10-03 03:55:57

标签: jquery placeholder

只要我的<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();
        }
    });
});

谢谢!

2 个答案:

答案 0 :(得分:1)

您希望绑定到focusblur事件,并将<span>绝对置于<textarea>之上。从一些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()调用是为了初始化<span>的状态,以便<textarea>以内容开始时它将处于正确的状态。

快速演示:http://jsfiddle.net/ambiguous/PLrf3/1/

BTW,在同一页面中id="placeholder"id="Placeholder"可能会导致一些混淆。最好为您的camelCase属性选择一个标准方案(words-and-hyphensid或其他)并坚持下去。只是一个案例差异可能会令人困惑,可能看起来像一个错字。

答案 1 :(得分:0)

这样的事情应该有效:

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

如果他们前面有span.holder,这应适用于页面上的所有textareas。

相关问题