首页 > 解决方案 > 输入框包含某些值时的浮动标签

问题描述

我正在创建一个元素,其中标签在元素聚焦时向上浮动,并在移除焦点时返回原始位置。

现在如果输入框包含一些值并且我们移除焦点,标签应该只保持向上。如何使用 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;
}

标签: javascripthtmlcss

解决方案


一个非常简单的方法是执行以下操作:

1- 添加required到输入
2- 编辑以下行:

input:focus + label {
  transform: translateY(-2px);
}

input:focus + label ,input:valid +label {
  transform: translateY(-2px);
}

从这里查看编辑后的代码


推荐阅读