标记焦点和非焦点时的移动

时间:2017-09-29 14:22:38

标签: jquery css

我试图找出如何在文本框内部显示标签并将标签移动到周边。我想要这样的一个示例是https://www.discover.com/的登录屏幕当您在用户ID或密码框内单击时,您将看到在您进出焦点时调整标签。

https://jsfiddle.net/bobrierton/Ls1c4fdj/

<div class="input-wrapper userid-wrapper">
    <label for="userid-content" class="user-id-label">User ID</label>
    <input type="text" class="form-control userid user-id-input" name="userID" id="userid-content" aria-required="true" data-toggle="popover" data-content="Please enter your User ID" maxlength="16" />
</div>
<div class="input-wrapper password-wrapper">
    <label for="password-content" class="password-label">Password</label>
    <input type="password" class="form-control password password-input" name="password" id="password-content" aria-required="true" data-toggle="popover" data-content="Please enter your Password" maxlength="32"/>
</div>

有人会帮助我如何能够像这样移动标签吗?

1 个答案:

答案 0 :(得分:1)

一种方法......

  1. 将标签设置为position: absolute,将其从文档流中取出,并将其放在input内。
  2. 使用inputmargin提供一些空间,以便为标签留出空间。
  3. 利用:focus-within。如果inputfocus,则可以定位标签。
  4. 设置label以执行您需要的操作。在下面的示例中,我减少了字体大小,并根据您问题中的示例重新定位它。
  5. fiddle

    .input-wrapper {
      position: relative;
    }
    
    .input-wrapper label {
      position: absolute;
      margin: 1em;
      transition: .5s ease-in-out;
      top: 0;
    }
    
    .input-wrapper input {
      margin: 1em;
    }
    
    .input-wrapper:focus-within label {
      font-size: .8em;
      top: -1em;
    }
    <div class="input-wrapper userid-wrapper">
      <label for="userid-content" class="user-id-label">User ID</label>
      <input type="text" class="form-control userid user-id-input" name="userID" id="userid-content" aria-required="true" data-toggle="popover" data-content="Please enter your User ID" maxlength="16" />
    </div>
    <div class="input-wrapper password-wrapper">
      <label for="password-content" class="password-label">Password</label>
      <input type="password" class="form-control password password-input" name="password" id="password-content" aria-required="true" data-toggle="popover" data-content="Please enter your Password" maxlength="32" />
    </div>