【问题标题】:css/javascript form onfocus placeholder text still there, on typing disappearcss/javascript 表单 onfocus 占位符文本仍然存在,输入时消失
【发布时间】:2011-10-16 17:36:03
【问题描述】:

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

【问题讨论】:

  • 有一个placeholder 属性供支持它的浏览器使用,你可以使用jquery plugin,或者几行js...或者使用SO search box

标签: javascript css forms


【解决方案1】:

他们没有使用 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 来添加和删除输入字段的 changekeyUp 上的 input_wrapper_focus/notempty 类,这取决于你的 JavaScript 库与否- 图书馆决定。

【讨论】:

  • 谢谢。正是我需要的答案。
猜你喜欢
  • 2017-11-12
  • 2018-12-30
  • 2022-01-13
  • 2017-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-02-14
  • 2014-01-04
  • 2020-10-27
相关资源
最近更新 更多