用于select在另一个元素之前出现的元素的CSSselect器?
我正在为我的网站devise一个login页面,当文本框获得焦点时,我想大胆地在input框前面加上标签。 现在我有以下的标记:
<label for="username">Username:</label> <input type="textbox" id="username" /> <label for="password">Password:</label> <input type="textbox" id="password" /> 我可以使用相邻的select器在文本框之后select标签,但是我无法select它之前的元素。 我可以使用这个CSSselect器规则,但是它只能在后面select标签,所以当用户名文本框获得焦点时,密码标签变为粗体。
 input:focus + label {font-weight: bold} 
有什么我可以做的这个工作? 我知道JavaScript可以用来轻松地做到这一点,但如果可能的话,我想使用一个纯粹的基于CSS的解决scheme,我只是想不出一个办法来做到这一点。
 如果input在label之前,则可以使用“邻接兄弟select器”。 只需将input放在label之前,然后在input之前修改布局以放置label 。 这是一个例子: 
 <head runat="server"> <title></title> <style type="text/css"> input:focus + label {font-weight: bold} </style> </head> <body> <form id="form1" runat="server"> <div style="direction:rtl"> <input type="text" id="username" /> <label for="username">Username:</label> </div> <div style="direction:rtl"> <input type="password" id="password" /> <label for="password">Password:</label> </div> </form> </body> 
(这是一种黑客,我会亲自使用JavaScript来做到这一点)
 input:focus + label {font-weight: bold} 
 <form id="form1" runat="server"> <div style="direction:rtl"> <input type="text" id="username" /> <label for="username">Username:</label> </div> <div style="direction:rtl"> <input type="password" id="password" /> <label for="password">Password:</label> </div> </form> 
  CSS Selectors 4 Spec提供了一种语法来定义select器的“主题”,通过使用!  。 截至2016年初,这在任何浏览器中都不可用。 我包含了这个,因为一旦浏览器实现这个语法,它将成为使用纯CSS的正确方法。 
鉴于问题的标记
 <label for="username">Username:</label> <input type="textbox" id="username" /> <label for="password">Password:</label> <input type="textbox" id="password" /> 
这CSS将做伎俩。
 label:has(+ input:focus) {font-weight: bold} 
 当然,这假设浏览器实际上实现了主题select器,并且没有与这个语法如何处理:focus伪类相关的错误。 
有没有select器,会给你使用CSS的前一个元素..
你将需要使用JavaScript来处理你的事情。
使用这个select器:
 label[for=username] { font-weight: bold } 
这将select在属性'for'中具有值'username'的标签
将input元素向右移动,实现正确的元素顺序,而不改变在方向为rtl的标签文本中改变“用户名”和“:”的顺序。
 <style type="text/css"> form {text-align: right;} input:focus + label {font-weight: bold} input {float:right; clear:right;} </style> <form> <div> <input type="text" id="username" /> <label for="username">Username:</label> </div> <div> <input type="password" id="password" /> <label for="password">Password:</label> </div> </form> 
我在w3cschol中find了这个
  p~ulselect前面有<p>元素的每个<ul> <p>元素 
但是我的testing失败了。 我无法做到这一点。 可能是它没有被浏览器实现。