在早期,我们都是通过使用 JavaScript 来实现占位符功能。而现在,HTML5 原生提供的 placeholder 属性让我们在现代浏览器轻松就能实现这样的功能。这里向大家分享一个自适应的占位符效果(Adaptive Placeholder),当你输入的时候,提示文字不会消失,而是以动画的方式移动到了输入框的上方。
HTML:

<div style="width:400px;height:100px;margin:300px auto">
    <form>
        <input required="" type="text">
        <label alt="请输入名称" placeholder="名称"></label>
    </form>
</div>

css:

body {
    background-color: #FAFAFA;
}
.top-banner {
  background: #555;
}
input[type="text"] {
  -webkit-box-sizing: border-box;
  -moz-box-sizing: border-box;
  box-sizing: border-box;
  width: 100%;
  height: -webkit-calc(3em + 2px);
  height: calc(3em + 2px);
  margin: 0 0 1em;
  padding: 1em;
  border: 1px solid #cccccc;
  border-radius: 1.5em;
  background: #fff;
  resize: none;
  outline: none;
}
input[type="text"][required]:focus {
  border-color: #00bafa;
}
input[type="text"][required]:focus + label[placeholder]:before {
  color: #00bafa;
}
input[type="text"][required]:focus + label[placeholder]:before,
input[type="text"][required]:valid + label[placeholder]:before {
  -webkit-transition-duration: .2s;
  transition-duration: .2s;
  -webkit-transform: translate(0, -1.5em) scale(0.9, 0.9);
  -ms-transform: translate(0, -1.5em) scale(0.9, 0.9);
  transform: translate(0, -1.5em) scale(0.9, 0.9);
}
input[type="text"][required]:invalid + label[placeholder][alt]:before {
  content: attr(alt);
}
input[type="text"][required] + label[placeholder] {
  display: block;
  pointer-events: none;
  line-height: 2.3em;
  margin-top: -webkit-calc(-3em - 2px);
  margin-top: calc(-3em - 2px);
  margin-bottom: -webkit-calc((3em - 1em) + 2px);
  margin-bottom: calc((3em - 1em) + 2px);
}
input[type="text"][required] + label[placeholder]:before {
  content: attr(placeholder);
  display: inline-block;
  margin: 0 -webkit-calc(1em + 2px);
  margin: 0 calc(1em + 2px);
  padding: 0 2px;
  color: #898989;
  white-space: nowrap;
  -webkit-transition: 0.3s ease-in-out;
  transition: 0.3s ease-in-out;
  background-image: -webkit-gradient(linear, left top, left bottom, from(#ffffff), to(#ffffff));
  background-image: -webkit-linear-gradient(top, #ffffff, #ffffff);
  background-image: linear-gradient(to bottom, #ffffff, #ffffff);
  -webkit-background-size: 100% 5px;
  background-size: 100% 5px;
  background-repeat: no-repeat;
  background-position: center;
}

效果如图所示:
1.gif

Last modification:February 20, 2020
如果觉得我的文章对你有用,请随意赞赏