Skip to content

简易实现 MUI 的 input 组件样式 ​

2023-06-29 18:03:07

Material UI Input

实现了下 MUI Input 组件的样式,比较简单,主要是使用 valid 这个伪类,搭配 input 中的 required 属性,valid 伪类在 输入框中有值时触发

按照这个思路,在聚焦输入框和输入框中有值时通过定位和其他 css 样式做一些效果,就有了 MUI 的样式

<template>
  <div fcc h-100px>
    <div class="wrap">
      <input class="input" type="text" required id="input" />
      <span class="bar"></span>
      <label class="label" for="username">User Name</label>
    </div>
  </div>
</template>
<style scoped>
.wrap {
  width: 300px;
  height: 50px;
  position: relative;
}

.input {
  width: 100%;
  height: 100%;
  font-size: 16px;
}

.bar {
  width: 60px;
  z-index: 10;
  height: 2px;
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translate(-50%, -50%);
  background: #5264ae;
  transition: 0.4s;
}

.label {
  position: absolute;
  left: 0;
  bottom: 15px;
  z-index: -1;
  transition: 0.4s;
  font-size: 20px;
  opacity: 0.8;
}

#input:valid ~ .bar,
#input:focus ~ .bar {
  width: 100%;
}

#input:valid ~ .label,
#input:focus ~ .label {
  bottom: 40px;
  font-size: 16px;
  color: #5264ae;
}
</style>

Released under the MIT License.