首页 > 解决方案 > 输入为 :valid 时无法控制 ::after

问题描述

似乎无法控制div::after里面的输入是什么时候:valid

有人可以帮忙吗? https://jsfiddle.net/Mengolor/0akjcsvf/

input.your-name {
	height: auto;
	width: 200px;
	border: 1px solid lightgray;
	border-radius: 2px;
	padding: 24px 0px 4px 4px;
}

div.nf-field-element::after {
	position: absolute;
	top: 29px;
	left: 12px;
  content: "Example";
	color: black;
	font-size: 100%;
	transition: 0.2s;
}

div.nf-field-element:focus-within::after {
	top: 14px;
	color: lightgray;
	font-size: 70%;
}

input:focus {
	outline: none;
}

input:valid {
		border: 1px solid green;
}

/* CSS ONLY | When the field is filled the 'Example' label should stay up */
<div class="nf-field-element">
  <input type="text" class="your-name" placeholder=" " required>
</div>

仅供参考,无法更改 HTML 代码

如果 JS 是解决方案,脚本将如何?我对JS没有经验

洛伦佐

标签: htmlcss

解决方案


我不认为你可以使用伪选择器来做到这一点。

如果需要,您可以添加 a label,并使用以下代码获得所需的行为:

<div class="nf-field-element">
  <input type="text" class="your-name" placeholder=" " required>
  <label>Example</label>
</div>
label {
  position: absolute;
  top: 29px;
  left: 12px;
  color: black;
  font-size: 100%;
  transition: 0.2s;
}

div.nf-field-element:focus-within label,
input:valid + label {
 top: 14px;
 color: lightgray;
 font-size: 70%;
}

这是一个工作示例


推荐阅读