css / javascript表单onfocus占位符文本仍然存在,在输入时消失

时间:2011-07-31 00:04:29

标签: javascript css forms

我只想弄清楚如何制作像www.tumblr.com这样的表格。 onFocus占位符保留在输入框中,但在键入时,占位符文本将消失。我知道如何通过另一个找到here的教程来完成onFocus,但我想知道他们如何将该背景文本保留在onFocus上,但只是在输入时更改它。

1 个答案:

答案 0 :(得分:2)

他们没有使用onFocus技巧来更改文本。事实上,它们将两个绝对定位的块元素分层在一个单独的相对定位的块元素中。

然后,他们等待onKeyUp或类似事件,并隐藏“label”元素。

如果在Firefox中使用Firebug,则可以轻松查看创建效果的节点和CSS。它看起来像这样:

<强> HTML

<div class="input_wrapper">
    <label for="user_email">Email</label>
    <input type="text" id="user_email" name="user_email" />
</div>

<强> CSS

.input_wrapper {
    position: relative;
}
.input_wrapper label {
    position: absolute;
    top: 2px;
    left: 5px;
    z-index: 1; /* stack below input */
}
.input_wrapper_focused label {
    /* style label for focused input */
}
.input_wrapper_notempty label {
    visibility: hidden;
}
.input_wrapper input {
    position: absolute;
    top: 0;
    left: 0;
    z-index: 2; /* stack above input */
}

你需要设计和调整这些元素以使它们看起来漂亮。此外,请注意他们足够聪明,可以将标签放在第一位 - 这样屏幕阅读器仍然可以按照正确的顺序查看内容。

然后你需要添加JS来添加和删除输入字段的 change keyUp 上的input_wrapper_focus / notempty类,这取决于你的JavaScript库或非 - 图书馆决定。