問題描述
我正在為我的網站創建一個登錄頁面,我想在文本框獲得焦點時將輸入框之前的標簽加粗.現在我有以下標記:
I'm working on a login page for my website and I want to bold the label that comes before the input box when the text box gains focus. Right now I have the following markup:
<label for="username">Username:</label>
<input type="textbox" id="username" />
<label for="password">Password:</label>
<input type="textbox" id="password" />
我可以使用相鄰選擇器選擇標簽after文本框,但我不能選擇它之前的元素.我可以使用這個 CSS 選擇器規則,但它只選擇后面的標簽,所以當用戶名文本框獲得焦點時,密碼標簽變為粗體.
I can use the adjacent selector to select the label after the text box, but I can't select the element before it. I can use this CSS selector rule, but it only selects the label after, so when the username text box gains focus, the password label becomes bold.
input:focus + label {font-weight: bold}
我能做些什么來完成這項工作嗎?我知道 JavaScript 可以很容易地做到這一點,但如果可能的話,我想使用一個純基于 CSS 的解決方案,我只是想不出辦法.
Is there anything I can do to make this work? I know JavaScript could be used to easily do this, but I'd like to use a purely CSS-based solution if possible, I just can't figure out a way to do it.
推薦答案
如果 input
在 label
之前,則可以使用相鄰兄弟選擇器".只需將 input
放在 label
之前,然后修改布局將 label
放在 input
之前.這是一個例子:
It would be possible to use the 'adjacent sibling selector' if the input
was before the label
. Just put the input
before the label
, and then modify the layout to put label
before the input
. Here's an example:
<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>
(這是一種 hack,我個人會使用 javascript 來做到這一點)
(It's kind of a hack, I would personally use javascript to do this)
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選擇器用于選擇另一個元素之前的元素?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!