【问题标题】:How to check if input is empty and apply class to it?如何检查输入是否为空并对其应用类?
【发布时间】:2017-08-08 11:41:58
【问题描述】:

我想重新创建这个效果如下(Hoshi): https://tympanus.net/Development/TextInputEffects/

我已经查看了这个 JS 并用谷歌搜索了一些验证器,但是当我在输入中输入文本时,我无法理解如何做到这一点,标签停留在那里。在我的情况下,当我输入文本并离开输入时,标签会向下移动。

【问题讨论】:

  • 你的代码在哪里??

标签: javascript jquery css forms


【解决方案1】:

我创建了一个如何做到这一点的最小示例。 在代码中查看我的 cmets 以了解其工作原理。

$("#input").focus(function() {
  // If you enter the input

  $("#test").animate({ // Animate the text to the top
    top: "20px",
  }, 200, function() {});

}).blur(function() {
  // If you left the input

  if ($(this).val() == "") { // Only if the input is empty

    $("#test").animate({ // Animate the text back into the input
      top: "50px",
    }, 200, function() {});
  }
});
#box {
  height: 100px;
  width: 100px;
  padding-top: 50px;
  position: relative;
}

#test {
  top: 50px;
  left: 5px;
  position: absolute;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="box">
  <input type="text" id="input"><span id="test">Test</span>
</div>

【讨论】:

    【解决方案2】:

    这样的事情可以很容易地实现,而无需使用纯 CSS 编写一行 JavaScript。我在下面添加了一个 sn-p 来演示基本思想。我将required attribute 用于输入,并结合:valid css selector 来检查输入是否为空。

    label {
      display: inline-block;
      margin-top: 20px;
      position: relative;
    }
    
    label > span {
      position: absolute;
      cursor: text;
      left: 2px;
      top: 1px;
      transition: top .2s ease;
      color: #3a3a3a;
    }
    
    label > input:focus + span,
    label > input:valid + span{
      top: -20px;
    } 
    <label>
      <input required type="text" />
      <span>Surname</span>
    </label>

    【讨论】:

      猜你喜欢
      • 2020-09-20
      • 2018-05-26
      • 2021-09-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-12-23
      • 2013-01-05
      相关资源
      最近更新 更多