我只是想弄清楚如何制作像 www.tumblr.com 这样的表单。 onFocus 占位符保留在输入框中,但是当开始输入时占位符文本消失。我知道如何通过找到的另一个教程进行 onFocus here ,但我想知道他们如何将背景文本保持在焦点上,但只在键入时更改它。
最佳答案
他们没有使用 onFocus 技巧来更改文本。事实上,它们将两个绝对定位的 block 元素分层放置在一个单独的相对定位的 block 元素中。
然后,他们等待 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 库或非-图书馆的决定。
关于javascript - css/javascript 表单 onfocus 占位符文本仍然存在,在键入时消失,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6886697/