他们没有使用 onFocus 技巧来更改文本。实际上,它们是将两个绝对定位的块元素分层在一个单独的相对定位的块元素中。
然后,他们等待 onKeyUp 或一些类似的事件,并隐藏“标签”元素。
如果您在 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 库与否- 图书馆决定。