如何创建这样的 bootstrap 标签?

How to create bootstrap labels like this?

我想创建这样的输入。单击标签时,会出现一条紫色线。当您单击成功输入时,标签下方会出现绿线。当您单击错误行输入时,输入下方会出现红线。

我想使用 html 和 css

创建

这应该是最低限度的实现。

input[type="text"] {
 outline: none;
 background: transparent;
 border: none;
    border-bottom: 1px solid gray;
 margin: 5px 15px;
 line-height: 1.4em;
}

.has-success input:focus, .has-success input:active {
 border-bottom: 1px solid green;
 color: green;
}

.has-error input:focus, .has-error input:active {
 border-bottom: 1px solid red;
 color: red;
}
<div class="has-success">
  <input type="text" value="success">
</div>

<div class="has-error">
  <input type="text" value="error">
</div>

有一种方法可以使用纯 HTML 和 CSS。

也许你甚至可以优化代码,但我想给你一个快速的想法。

HTML

<div class="wrapper">
  <input id="name" type="text" placeholder="Username" />
  <label for="name"></label>
</div>

CSS

.wrapper {
  position: relative;
  width: 200px;
}

input {
  width: 100%;
  background: none;
  padding: 10px;
  border: none;
  outline: none;
  margin-top: 10px;
}

label {
  position: absolute;
  top: 100%;
  left: 0;
  width: 100%;
  height: 2px;
  background: rgba(0, 0, 0, 0.4);
}

label:after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 0;
  height: 2px;
  background: rgba(0, 0, 0, 0.8);
  transition: 0.4s;
}

input:focus ~ label:after {
  width: 100%;
}

演示

Codepen Pen

Material Inputs with a floating Label

For those of you who want to add the functionality of floating labels.

与第一个想法相比,我尽量保持 HTML 结构相似。终于可以使用这种结构了。只需从输入中删除占位符标记,并在父级 div 上添加一个名为占位符的数据属性。这是稍后在输入焦点上向上滑动效果所需要的。 此外,您还需要一点 JavaScript,因为您必须向父元素添加 class。

HTML

<div class="wrapper" data-placeholder="Username">
    <input id="name" type="text" />
    <label for="name"></label>
</div>

CSS

.wrapper {
  position: relative;
  width: 200px;
}

input {
  width: 100%;
  background: none;
  padding: 10px;
  border: none;
  outline: none;
}

label {
  position: absolute;
  top: 100%;
  left: 0;
  width: 100%;
  height: 2px;
  background: rgba(0, 0, 0, 0.4);
}

label:after {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 0;
  height: 2px;
  background: rgba(0, 0, 0, 0.8);
  transition: 0.4s;
}

input:focus ~ label:after {
  width: 100%;
}

.wrapper:before {
  content: attr(data-placeholder);
  position: relative;
  top: 30px;
  left: 10px;
  color: rgba(0, 0, 0, 0.4);
  transition: 0.3s;
  z-index: -1;
}

.wrapper.clicked:before {
  color: #000;
  top: 0;
  left: 0;
}

 .wrapper.clicked.filled:before {
  color: rgba(0,0,0,0.4);
}

jQuery

$("input").focus(function() {
  $(this).parent().addClass("clicked");
  if ($(this).val().length > 0) {
    $(this).parent().removeClass("filled");
  }
});

$("input").blur(function() {
  if ($(this).val().length > 0) {
    $(this).parent().addClass("filled");
  } else {
    $(this).parent().removeClass("clicked filled");
  }
});

演示

Codepen Pen