📜  单击时不制作输入框边框 (1)

📅  最后修改于: 2023-12-03 15:07:20.806000             🧑  作者: Mango

单击时不制作输入框边框

在很多情况下,我们希望输入框在被点击时不出现边框,而是保持原来的样式。本文将介绍如何在HTML和CSS中实现这一效果。

HTML

在HTML中,我们需要对输入框的<input>标签添加一个 <span>元素。在单击<input>标签时,我们将在该<span>元素上添加一个类is-focused,这样就可以控制输入框的样式。

下面是示例代码:

<div class="input-container">
  <input type="text" name="input" />
  <span class="focus-border"></span>
</div>
CSS

在CSS中,我们可以使用伪类:focus来定义输入框被聚焦时的样式。为了实现本文的效果,我们需要在这里清除输入框的边框样式。同时,我们还需要定义一个.focus-border类,用于展示输入框聚焦时的边框效果。

下面是示例代码:

.input-container {
  position: relative;
  width: 100%;
  height: 3.5rem;
  margin-bottom: 2rem;
}

input[type="text"],
input[type="email"],
input[type="password"] {
  font-size: 1.6rem;
  color: #8d8d8d;
  width: 100%;
  height: 100%;
  padding: 1rem 1rem 0;
  border-radius: 0;
  background: none;
  border: none;
  border-bottom: 1px solid #c4c4c4;
  transition: border-bottom-width 0.3s;
}

input[type="text"]:focus,
input[type="email"]:focus,
input[type="password"]:focus {
  outline: none;
  background: none;
  border-color: #0071ff;
}

.focus-border {
  position: absolute;
  bottom: 0;
  left: 0;
  width: 0;
  height: 2px;
  background-color: #0071ff;
  transition: width 0.3s ease;
}

input[type="text"]:focus ~ .focus-border,
input[type="email"]:focus ~ .focus-border,
input[type="password"]:focus ~ .focus-border {
  width: 100%;
}

在上面的代码中,我们给.input-container元素设置了一个相对定位,并让输入框和边框都填满了该元素。我们还对输入框的样式进行了一些调整,使其与设计相符。

注意到我们在输入框的:focus样式中将边框颜色设置为了蓝色,但没有指定边框的宽度。这样就可以清除输入框被聚焦时的默认边框,并保留原有的样式。

最后,我们定义了.focus-border类来实现边框效果。该类设置了一个绝对定位,并占据了.input-container元素的底部。当输入框被聚焦时,我们通过添加.focus-border类来展示边框效果。

总结

本文介绍了如何在HTML和CSS中实现“单击时不制作输入框边框”的效果。通过设置输入框和边框的样式,我们可以实现原生的,看起来美观的输入框。