目前我正在尝试仿照这个示例。它工作得很好,但是有一个很大的限制:它只能在输入类型为文本时使用。
当您使用另一种输入类型,比如电子邮件时,基本字符串无效,因此占位符会掉落在文本上。
所以在我看来,解决这个问题有两种方案:
- 在所有地方都使用type=text,这有点糟糕,因为例如在手机上,您将无法获得电子邮件类型的键盘。
- 使用JavaScript检查输入是否具有值。
我希望我错过了什么,还有另一个示例可以实现我想要的功能。在完美的世界中,空输入不会被验证,因此占位符将显示其正常状态。然后当用户填入任何数据时,验证将开始。这是否可能通过纯CSS实现?
感谢大家!
HTML:
<fieldset id="fieldset1">
<input type="text" required />
<label>First name</label>
</fieldset>
<fieldset id="fieldset2">
<input type="email" required />
<label>Email address</label>
</fieldset>
CSS样式表:
fieldset {
position: relative;
margin:40px 0 0 0;
padding:0;
border:none;
}
fieldset input {
height: 2.5rem;
line-height: 2.25rem;
padding: 0 0.9375rem;
color: white;
font-size: 0.75rem;
font-weight: 700;
border: none;
outline: none !important;
-webkit-box-shadow: none !important;
box-shadow: none !important;
background: #9a9a9a;
display: block;
width: 100%;
border: 2px solid transparent;
-webkit-transition: all 100ms ease-out;
transition: all 100ms ease-out;
border-radius: 0px !important;
-webkit-border-radius: 0px !important;
}
fieldset label {
position: absolute;
color: white;
font-size: 0.75rem;
text-transform: uppercase;
font-weight: bold;
-webkit-transition: all 100ms ease-out;
transition: all 100ms ease-out;
line-height: 2.5rem;
left: 0.9375rem;
top: 0;
display: block;
text-align: left;
}
fieldset input:focus + label,
fieldset input:valid + label {
top: -1.875rem;
color: black;
}
我制作了一个JSFiddle来说明我的问题,您可以在这里查看它:here 编辑:由于1l13v不清楚我想要实现什么,所以我会重复一遍:我知道字符串不是有效的电子邮件地址,因此我现在的解决方案永远不会与除文本之外的任何其他输入类型一起使用。
我想做到以下几点:
- 有一个纯CSS的解决方案来检查输入是否具有任何值。如果为空,我可以显示占位符在其正常位置上,否则,我可以将占位符显示在输入框上方。
- 当输入完全为空时,使input[type="email"]:invalid返回false。
我使用了这个作为我的解决方案:
function checkInputValue() {
if($(this).val() !== ''){
$(this).parents('fieldset').addClass('valid');
} else {
$(this).parents('fieldset').removeClass('valid');
}
};
$('.input1').on('blur', checkInputValue); // Check if input has a value