繁体   English   中英

选择表单中的第一个非隐藏输入

[英]Selecting the first non-hidden input in a form

我试图选择非type="hidden"形式的第一个输入。

考虑以下形式:

<form>
  <input type="hidden" name="token" value="ABC123">
  <input type="text" name="username">
  <input type="password" name="password">
</form>

如果我想将特定样式应用于用户名字段。 我以为我可以使用它或类似的东西。 但是,到目前为止,我没有尝试过。

input:not([type=hidden]):first-child {
  background: orange;
}

我什至可以使用input[type=text]:first-child但这也不起作用。

这是我在写这个问题时使用的小提琴

您的示例不起作用,因为:first-child伪类仅在元素是第一个子元素的情况下才选择元素。 由于第一个非隐藏input元素不是第一个孩子,因此未选择任何内容。


根据您提供的HTML,可以使用选择器的组合来实现此目的。

第一个选择器可以是input:not([type="hidden"]):first-of-type ,以便选择任何非隐藏的input元素(如果它是第一个类型的话)。

如果下一个选择器是第一个类型,则下一个选择器选择隐藏的input元素,然后利用相邻的同级组合器+来选择下一个接下来的非隐藏的input元素:

 input:not([type="hidden"]):first-of-type, input[type="hidden"]:first-of-type + input:not([type="hidden"]) { background: orange; } 
 <form> <input type="hidden" name="token" value="ABC123"> <input type="text" name="username"> <input type="hidden" name="token" value="ABC123"> <input type="password" name="password"> </form> 

由于:first-of-type伪类通过其类型选择第一个元素,因此即使第一个子元素是图例也可以使用:

 input:not([type="hidden"]):first-of-type, input[type="hidden"]:first-of-type+input:not([type="hidden"]) { background: orange; } 
 <form> <fieldset> <legend>Title</legend> <input type="hidden" name="token" value="ABC123"> <input type="text" name="username"> <input type="hidden" name="token" value="ABC123"> <input type="password" name="password"> </fieldset> </form> 


但是,由于您声明隐藏的input元素始终始终是第一个,因此以下选择器就足够了:

 input[type="hidden"]:first-of-type + input:not([type="hidden"]) { background: orange; } 
 <form> <input type="hidden" name="token" value="ABC123"> <input type="text" name="username"> <input type="hidden" name="token" value="ABC123"> <input type="password" name="password"> </form> 

但是请记住,如果有两个连续的隐藏input元素(如下面的示例),则此方法将无效。 要解决这种情况,您需要执行其他答案所建议的操作,并选择所有input元素,然后使用通用的同级组合器~覆盖所有以下同级元素。 如果您的HTML与上述任何示例不同,我建议您这样做。

 input:not([type="hidden"]):first-of-type, input[type="hidden"]:first-of-type+input:not([type="hidden"]) { background: orange; } 
 <p> Example demonstrating that it doesn't work with two consecutive hidden input elements: </p> <form> <fieldset> <legend>Title</legend> <input type="hidden" name="token" value="ABC123"> <input type="hidden" name="token" value="ABC123"> <input type="text" name="username"> <input type="hidden" name="token" value="ABC123"> <input type="password" name="password"> </fieldset> </form> 

因此,问题在于CSS转换为“如果未隐藏其类型,则选择第一个输入子项”,因为该类型是隐藏的,所以CSS不适用。

相反,您需要做的是使CSS应用于所有未隐藏的输入,然后对不是第一个的所有同级关闭它(这对我在Chrome上有效)

 input:not([type="hidden"]) { background: orange; } input:not([type="hidden"]) ~ input:not([type="hidden"]) { background: white; } 
 <form> <input type="hidden" name="token" value="ABC123"> <input type="text" name="username"> <input type="password" name="password"> </form> 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM