【问题标题】:Remove html label tag text when value is entered - with CSS输入值时删除 html 标签标记文本 - 使用 CSS
【发布时间】:2021-09-07 19:13:39
【问题描述】:

因此,每当有人输入值时,我都会尝试从我的输入 html 标记中删除标签及其值,而我现在拥有的代码可以完成这项工作,但它只会在我单击输入时删除该值盒子。一旦我输入一个值,标签就会与输入的值一起卡在那里。有人可以帮我制作它,以便标签被完全删除,而不仅仅是在点击它时。这是我可以用css做的吗?如果我不能,那么我将如何使用 javascript 来做到这一点?

.text-input-wrapper {
  position: relative;
}

.text-input-wrapper label {
  position: absolute;
  left: 0;
}

.text-input-wrapper label::before {
  transition: 0s;
}

.text-input-wrapper label.icon1::before {
  content: 'Email';
}

.text-input-wrapper label.icon2::before {
  content: 'Password';
}

.text-input-wrapper input {
  padding: 0 2rem 0;
}

.text-input-wrapper input:focus+label::before,
.text-input-wrapper input:active+label::before {
  display: none;
}
<form class="clearfix credentials-form login-form" method="POST">

  <div class="credentials-form__fields">

    <div class="text-input standard login-text-input login-email">

      <div class="text-input-error-wrapper">
      </div>

      <div class="text-input-wrapper">

        <input type="email" id="login_email2812380460348143" class="text-input-input" name="login_email" value="" autocomplete="off" aria-invalid="false" inputmode="text">

        <label for="login_email2812380460348143" class="icon1"></label>

      </div>
    </div>

    <div>

      <div class="tooltip-container">
      </div>

      <div class="text-input standard login-text-input login-password">

        <div class="text-input-error-wrapper">
        </div>

        <div class="text-input-wrapper">

          <input type="password" id="login_password5101720956289264" class="text-input-input password-input" name="login_password" value="" autocomplete="off" aria-invalid="false" inputmode="text">
          <label for="login_password5101720956289264" class="icon2"></label>
        </div>
      </div>
    </div>
  </div>

  <button class="login-button signin-button button-primary" type="submit">
    
                            <div class="signin-text">Sign in
                            </div></button>
</form>

【问题讨论】:

  • "[我] 试图从我的输入 html 标记中删除标签及其值" - 出于可访问性(和用户体验)的原因,请不要这样做,标签应始终对用户可见。
  • 标签文本在输入中。我想在有人输入他们的详细信息时删除它
  • @ruzter 而不是删除标签...当用户输入详细信息时将其显示在输入上方
  • @ruzter 尝试看看如何根据输入数据来扩大和缩小标签
  • 是的,我明白你们在说什么,但我的页面设计不允许我这样做,这就是为什么我需要一种在输入值时删除标签的方法。

标签: javascript html css


【解决方案1】:

试试这个方法……

const inputs = document.querySelectorAll('.text-input-wrapper input');
const labels = document.querySelectorAll('.text-input-wrapper label');

inputs.forEach((input, i) => {
   input.addEventListener('input', () => {
      labels[i].style.opacity = 0;
   });
});

【讨论】:

  • 在您的示例中打错了字,每次值更改时它也会发出相当嘈杂的声音。
  • @ChrisW。哎呀你是对的。现在修复。也许focus 事件的噪音较小,但 OP 只想在输入某个值时隐藏标签...
【解决方案2】:

使用onInput 事件而不是onChange 事件。

【讨论】:

    猜你喜欢
    • 2015-12-02
    • 2014-01-28
    • 2011-07-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-11-23
    • 2020-07-08
    • 1970-01-01
    相关资源
    最近更新 更多