首页 > 解决方案 > 这种类型的输入标签是如何实现的?

问题描述

我试图弄清楚这些 HTML 输入是如何实现的:

在此处输入图像描述

Google 使用这些输入,其中占位符过渡到角落并在单击输入后成为标签。我以为他们以某种方式使用<fieldset>with<legend>来完成此任务,但检查代码显示他们正在使用带有 div 的输入。有没有一种本地方法可以做到这一点,我还没有听说过,或者有人知道这是怎么回事完成了吗?

示例链接

标签: javascripthtmlcss

解决方案


您可以使用条件选择器仅使用 html+css 来执行此操作。小提琴示例:

main {
  position: absolute;
  font-size: 18px;
  font-family: sans-serif;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
}

input {
  font-size: inherit;
  font-family: inherit;
  border-radius: 4px;
  border: solid lightgray 1px;
  padding: 16px;
  min-width: 300px;
}

input + label {
  position: absolute;
  top: 8px;
  left: 10px;
  color: gray;
  transition: transform 0.2s;
  background: white;
  padding: 10px;
  pointer-events: none;
}

input:focus + label {
  transform: scale(0.75) translate(-24px, -40px);
}
<main>
  <input name="foo" />
  <label for="foo">Click the Input</label>
</main>


推荐阅读