改变现有的 jQuery 以制作跨度占位符
我有一些 jQuery,只要我的 与
input
名称和 ID 匹配,它就会提供占位符。然而,情况并非如此,因此我决定仅使用 作为占位符。有人可以帮助改变我的 jQuery 以使我正在使用的
类“holder”工作吗?目标是让占位符保持焦点,在输入存在时消失,然后在输入消失时重新出现。
这是我正在使用的 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();
}
});
});
谢谢!
I have some jQuery that provides a placeholder as long as my <label for="">
matches the input
name and ID. However, that's not the case so I've decided to just use a <span>
for the placeholder instead. Can someone help alter my jQuery to make the <span>
class "holder" I'm using work? The goal is to have the placeholder stay on focus, disappear when input exists, then reappear if the input disappears.
Here's the HTML I'm using:
<div id="placeholder">
<span class="holder">This is the placeholder...</span>
<%= f.text_area :body, :id =>"Placeholder" %>
</div>
And my current jQuery:
$(document).ready(function() {
$('textarea').keyup(function() {
if ($(this).val().length) {
$('label[for="' + $(this).attr('name') + '"]').hide();
} else {
$('label[for="' + $(this).attr('name') + '"]').show();
}
});
});
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您想要绑定到
focus
和模糊
事件并将绝对定位在
上<文本区域>
。从一些 CSS 开始:然后是 jQuery:
最后的
$('#Placeholder').blur()
调用用于初始化的状态这样,如果
还有一个快速演示: http://jsfiddle.net/ambigously/PLrf3/1/
顺便说一句,在同一页面中使用
id="placeholder"
和id="Placeholder"
可能会导致一些混乱。您最好为id
属性选择标准方案(camelCase
、words-and-hyphens
或其他)并坚持使用。仅大小写差异可能会令人困惑,并且可能看起来像是拼写错误。You want to bind to the
focus
andblur
events and absolutely position the<span>
over the<textarea>
. Start with some CSS:And then the jQuery:
The final
$('#Placeholder').blur()
call is there to initialize the state of the<span>
so that it will be in the right state if the<textarea>
starts out with content.And a quick demo: http://jsfiddle.net/ambiguous/PLrf3/1/
BTW, having
id="placeholder"
andid="Placeholder"
in the same page might lead to some confusion. You would be better off choosing a standard scheme (camelCase
,words-and-hyphens
, or whatever) for yourid
attributes and sticking to it. Just a case difference might be confusing and might look like a typo.像这样的东西应该有效:
如果页面上的所有文本区域前面都有
span.holder
,那么这应该适用于它们。Something like this should work:
This should work for all textareas on page if they have
span.holder
preceding them.