Radio button change css when clicked

早过忘川 提交于 2020-01-06 19:36:56

问题


Please take a look at http://jsfiddle.net/JHMqG/

I'm trying to figure out how to change the background of the radio button when clicked.

So far, I've been successful with the cat option, but I'm stuck at the dog option. I need the dog option to work because I want the background change to include the circle button.

Please advise. Thank you.


回答1:


See this:

DEMO

I changed a bit the HTML:

<div>
<input type="radio" name=1 Value=420 id="a1">
<label for="a1" class="radiostyle" >Cat ($420)</label>
</div>
<div>
    <input type="radio" name=1 Value=375 id="a2">
    <label for="a2" class="radiostyle">Dog ($375)</label>
</div>

and added a few bits to the CSS, so it now looks like this:

div { margin: .5em; }
input, label {
    position: relative;
    display: inline-block;
    vertical-align: middle;
}
input[type=radio] { margin-right: -1.65em; z-index: 2; }
.radiostyle{
    background-color: #CCC;
    border-radius: 8px;
    padding: 4px 4px 4px 1.75em;
}

.radiostyle:hover{
    background-color: #0F6;    
    cursor:pointer;
}

input[type=radio]:checked+label {
    /* Or `#a1:checked+label` if you only want it for that input */
    background-color: #0F6;
}



回答2:


Here you go: http://jsfiddle.net/JHMqG/1/
On the dog, the label element only contained the text. On the cat, the label element contained the text and the radio button. Also, I cleaned up your HTML a bit.




回答3:


The problem was the <input> was just preceding the <label> in the cat option, but in the dog option the <input> was inside the<label.

I corrected it by moving the <input> of the dog option to be preceding the label, you can see it working here:

http://jsfiddle.net/SxPvz/



来源:https://stackoverflow.com/questions/12437381/radio-button-change-css-when-clicked

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!