javascript - 输入框包含某些值时的浮动标签
问题描述
我正在创建一个元素,其中标签在元素聚焦时向上浮动,并在移除焦点时返回原始位置。
现在如果输入框包含一些值并且我们移除焦点,标签应该只保持向上。如何使用 CSS 实现这一点?
jsbin链接:https ://jsbin.com/furujub/edit?html,css,output
main.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width">
<title>JS Bin</title>
</head>
<body>
<div class='floating_input'>
<div class="field">
<input type="text">
<label>Name</label>
</div>
</div>
</body>
</html>
main.css
.floating_input {
display: inline-block;
}
.field {
display: flex;
flex-direction: column;
}
label {
order: -1;
padding-left: 5px;
transition: all 0.3s ease-in;
transform: translateY(20px);
pointer-events: none;
}
input:focus + label {
transform: translateY(-2px);
}
input {
border: none;
border-bottom: 2px solid;
outline: none;
}
解决方案
一个非常简单的方法是执行以下操作:
1- 添加required
到输入
2- 编辑以下行:
input:focus + label {
transform: translateY(-2px);
}
至
input:focus + label ,input:valid +label {
transform: translateY(-2px);
}
推荐阅读
- github - 使用 github graphql api 获取用户曾经提交的所有存储库的列表
- android - Android 上的 Gradle 7:使用 AGP 7 中的新变体 api 添加 BuildConfigField
- python - Python & Azure cli 备份命令:拼写错误或系统无法识别
- solidity - 错误的返回值 uint256
- antlr - Antlr4 的 GRUN:如何使用?
- asp.net - 从另一个 URL 接近时找不到图像文件的相对路径
- google-sheets - Google表格中有没有办法跟踪连接的表格
- reactjs - React 在 localhost url 之后打开网站链接,而不是 https://websitelink
- android - DefaultManifestParser 在 AGP 7 中已弃用,替代品是什么
- reactjs - 从 React 中的历史对象获取 goBack 路径字符串