【问题标题】:Floating Labels with CSS not working when input type is set to Email当输入类型设置为电子邮件时,带有 CSS 的浮动标签不起作用
【发布时间】:2020-05-20 19:09:21
【问题描述】:

当我们输入标签浮动到顶部的内容时,我有一个输入文本框。当输入类型为“文本”时它工作正常,但如果输入文本框设置为输入“电子邮件”它停止工作,我需要一个解决方案让它工作。

.relPos {
  position: relative;
}

.upLabel {
  position: absolute;
  top: 0px;
  left: 0;
  transition: .3s;
  pointer-events: none;
}

.upInputs input {
  box-shadow: none;
}

.upInputs input:focus~.upLabel,
.upInputs input:valid~.upLabel {
  top: -15px;
  border: none;
}
<br>
<div class="relPos upInputs">
  <input type="text" required>
  <label class="upLabel">Type="Text"</label>
</div>
<br>
<div class="relPos upInputs">
  <input type="email" required>
  <label class="upLabel">Type="Email"</label>
</div>

<br>

【问题讨论】:

  • 您使用的是:valid,因此您需要输入一个有效的电子邮件,例如email@mail.com,它会起作用
  • 兄弟,有什么方法可以让它在输入任何东西时工作?

标签: html css pseudo-class


【解决方案1】:

:valid 只会在输入有效时触发,因此您需要一封电子邮件 (xxx@yyy.zz) 才能使其工作。相反,您可以考虑使用:placeholder-shown ref 并使用空占位符:

.relPos {
  position: relative;
}

.upLabel {
  position: absolute;
  top: 0px;
  left: 0;
  transition: .3s;
  pointer-events: none;
}

.upInputs input {
  box-shadow: none;
}

.upInputs input:focus~.upLabel,
.upInputs input:not(:placeholder-shown)~.upLabel {
  top: -15px;
  border: none;
}
<br>
<div class="relPos upInputs">
  <input type="text" required placeholder=" ">
  <label class="upLabel">Type="Text"</label>
</div>
<br>
<div class="relPos upInputs">
  <input type="email" required placeholder=" ">
  <label class="upLabel">Type="Email"</label>
</div>

<br>

:valid来说明问题

.relPos {
  position: relative;
}

.upLabel {
  position: absolute;
  top: 0px;
  left: 0;
  transition: .3s;
  pointer-events: none;
}

.upInputs input {
  box-shadow: none;
}

.upInputs input:valid~.upLabel {
  top: -15px;
  border: none;
}
<div class="relPos upInputs">
  <input type="email" required value="not an email">
  <label class="upLabel">Type="Email"</label>
</div>
<br>
<div class="relPos upInputs">
  <input type="email" required value="example@email.com">
  <label class="upLabel">Type="Email"</label>
</div>

【讨论】:

    猜你喜欢
    • 2015-11-28
    • 2016-02-09
    • 2012-11-29
    • 1970-01-01
    • 1970-01-01
    • 2020-12-09
    • 1970-01-01
    • 2015-06-13
    • 1970-01-01
    相关资源
    最近更新 更多