2017-07-25 23 views
0

我試圖編輯單選按鈕出現在CSS中的方式,並嘗試使用包含該按鈕的標籤並且不使用標籤進行功能。使用CSS修改無標籤按鈕fol =「id」?

換句話說,我不想用這個:

<input type="radio" name="rb" id="rb2" /> 
    <label for="rb2">Hello</label> 

我想用這樣的:

<label><input type="radio" name="rb" />Hello</label> 

這樣做的原因是,HTML是動態生成的,我不能在輸入中創建一個id或其他字段。當我添加css來修改按鈕/文本時,它不起作用,因爲它要求標籤僅在文本上,並且要使用「for」。這裏是CSS:

.container{ 
    display: block; 
    position: relative; 
    margin: 40px auto; 
    height: auto; 
    width: 500px; 
    padding: 20px; 
    font-family: 'Lato', sans-serif; 
    font-size:18px; 
    border:2px 
solid #ccc; 
overflow-y: scroll; 
resize: both; 
} 

.container input[type=radio]:checked ~ .check { 
    border: 5px solid #0DFF92; 
} 

.container input[type=radio]:checked ~ .check::before{ 
    background: #0DFF92; 
} 

.container input[type=radio]:checked ~ label{ 
    color: #0DFF92; 
} 

它的工作原理,如果我把

<div class="container> 
<input type="radio" name="rb" value="Hello" id=rb2"/> 
     <label for="rb2">Hello</label> 
<input type="radio" name="rb" value="Goodbye" id="rb3"/> 
     <label for="rb3">Goodbye</label> 
</div> 

但不能與

<div class="container> 
    <label> <input type="radio" name="rb" value="Hello">Hello</label> 
<label><input type="radio" name="rb" value="Goodbye">Goodbye</label> 
    </div> 

有什麼建議?非常感謝!

+0

如果你移動你的節點,你必須相應地安排你的CSS選擇器。你有自動提款機:'[radio]〜label''這意味着瀏覽器會尋找一個單選按鈕,然後將其所有標籤的兄弟姐妹作爲目標:在第二個例子中,你有作爲父母的單選按鈕的標籤,但是你沒有任何容納該佈局的CSS。實際上,包裝輸入的唯一好處是增加點擊面積。如果您不使用'for'和輸入id,則不需要標籤。您直接點擊收音機,只需使用:'input [type ='radio]:checked {color:red}' – zer00ne

回答

1

您必須使用javascript。你不能在css中導航dom樹,所以既然你希望輸入在標籤內,並且css根據輸入影響標籤,你必須使用js來檢測更改並應用對其父母的造型。

+0

謝謝。我還在學習! – Chris

+0

沒問題!你可以使用jquery,就像'$('input')。on('change',function(){$ this.parent()。addClass()});'或者你可以直接添加一個樣式。或者在函數內部,您可以檢查該值並根據該值設置樣式。 –