我正在为我的网站的登录页面工作,我想当文本框获得焦点时,在输入框之前加粗的标签。现在,我有以下标记:
<label for="username">Username:</label>
<input type="textbox" id="username" />
<label for="password">Password:</label>
<input type="textbox" id="password" />
我可以使用相邻的选择器在文本框之后选择标签,但不能选择它之前的元素。我可以使用这个CSS选择器规则,但它只选择之后的标签,所以当username文本框获得焦点时,密码标签将变为粗体。
input:focus + label {font-weight: bold}
我能做些什么来让它工作吗?我知道JavaScript可以很容易地做到这一点,但如果可能的话,我想使用一个纯粹基于CSS的解决方案,我只是想不出一个方法来做到这一点。
发布于 2009-01-29 18:39:52
如果input
在label
之前,则可以使用“相邻兄弟选择器”。只需将input
放在label
之前,然后修改布局,将label
放在input
之前。下面是一个例子:
<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>
发布于 2012-07-26 01:14:59
CSS Selectors 4 Spec提供了一种使用!
定义选择器的“主题”的语法。截至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}
当然,这假设浏览器实际实现了主题选择器,并且没有与此语法如何与:focus
伪类一起工作的bug。
发布于 2009-01-29 18:30:12
没有选择器可以提供使用CSS的前一个元素。
你需要使用javascript来处理你想要的东西。
https://stackoverflow.com/questions/492786
复制相似问题