【发布时间】:2019-09-11 18:40:14
【问题描述】:
我有这个样本:
编码 HTML:
<div class="field">
<label>First Name</label>
<div class="control">
<input type="text" class="input-text">
</div>
</div>
代码 CSS:
.field{
position: relative;
}
.label {
position: absolute;
pointer-events: none;
left: 10px;
top: 2px;
transition: 0.2s ease all;
font-size: 15px;
}
input:focus ~ .label,
input:not(:focus):valid ~ .label {
top: -6px;
}
基本上我希望当用户在输入中写一些东西时,标签会移到输入上。
只能从css中获取吗?
您能否更改我创建的示例以准确了解这是如何完成的?
提前致谢!
【问题讨论】:
-
when the user writes something in the input。这会生成一个事件,您可以使用 javaScript 但不能使用 CSS(仅)控制该事件。此外,选择器input:focus ~ .label将选择具有类label的输入的兄弟(在DOM 树的下方)。label和input不是兄弟姐妹。如果他们是,标签是在输入之前。 -
可能我没有正确表达自己,关于焦点事件,CSS中也存在这种情况
-
选择器
input:focus ~ .label将选择类label的input的兄弟姐妹(在DOM 树的下方)。label和input不是兄弟姐妹。如果是的话,label在input之前。你不能在 dom 树上选择元素,只能向下选择。 -
没有以前的兄弟选择器,也没有父选择器,所以你不能用纯 css 和你当前的 html 结构来做到这一点
-
在发布问题之前请进行更多研究。 You can check this out! This might help!