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