[英]Is there a pure CSS way to change checked radio button label's style when another label is hovered?
我正在設置標簽樣式,以代替標准的瀏覽器定義的單選按鈕控件。 我有一個:hover
樣式和:checked
樣式的標簽。
但目前尚不清楚單擊按鈕是否會“取消選中”當前選中的按鈕。 因此,當另一個標簽懸停時,我想更改選中標簽的樣式。
我已經編寫了一個示例( JSFiddle )。
當前行為:
(我的屏幕截圖工具將其刪除,但光標位於單選按鈕3上方。選中了單選按鈕1。)
所需行為:
HTML:
<form type="post">
<input type="radio" name="group" id="radio1" />
<label for="radio1">Radio Button One</label>
<input type="radio" name="group" id="radio2" />
<label for="radio2">Radio Button Two</label>
<input type="radio" name="group" id="radio3" />
<label for="radio3">Radio Button Three</label>
<input type="radio" name="group" id="radio4" />
<label for="radio4">Radio Button Four</label>
</form>
CSS:
input[type="radio"] {
display: none;
}
input[type="radio"] + label {
display: block;
width: 200px;
height: 30px;
text-align: center;
line-height: 30px;
background-color: white;
}
input[type="radio"] + label:hover {
background-color: blue;
color: white;
}
input[type="radio"]:checked + label {
background-color: red;
color: white;
}
如果必須使用JS,我會這樣做,但是純CSS是更好的選擇。
除非所選元素是后代或相鄰元素,否則由於級聯性質,您將很難使用CSS進行此操作。 但是,如果您的表單具有定義的邊界框,則可以通過CSS來利用父級的:hover狀態作弊,例如:
form:hover input[type="radio"]:checked + label {
background-color: pink;
}
這有點駭人聽聞,但可能會為您帶來預期的效果。 我希望這有幫助。
幸田來未
假設Kodaloid是正確的,並且沒有純CSS解決方案,這是一種使用jQuery( JSFiddle )實現此效果的方法。
我必須使用它,因為我正在處理的表單在按鈕之間有空格。
為選中的標簽添加其他類以使其變為粉紅色:
input[type="radio"]:checked + label.otherhover {
background-color: pink;
}
使用jQuery在適當的時間切換類:
$("input[type='radio'] + label").hover(
function () {
if (!$("#" + this.htmlFor).is(":checked")) {
$("input[type='radio']:checked + label").addClass("otherhover");
}
},
function () {
if (!$("#" + this.htmlFor).is(":checked")) {
$("input[type='radio']:checked + label").removeClass("otherhover");
}
}
);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.