Add class to radio button

做~自己de王妃 提交于 2020-01-14 22:40:06

问题


<input id="radio1" type="radio" name="rgroup" value="1" >
 <label for="radio1"><span><span></span></span>1</label>
<input id="radio2" type="radio" name="rgroup" value="2" >
 <label for="radio2"><span><span></span></span>1</label>

I have something like this and i want to add an image to the element which is checked using javaScript. How can i do it?


回答1:


Is it important for you to add a class for the radio which is checked? As you can do that simply with CSS:

#radio1:checked + label {
    color: #f00;
}

Demo

#radio1:checked + label:after {
    content: url(IMAGE_URL_HERE);
}

Demo 2 (With image embedded when you select the radio box)

Demo 3 (With tick image)




回答2:


Try this:

input[type="radio"]:checked + label {
    background-image: url("");
    background-repeat: no-repeat;
    background-position: center left; /* or center right */
}



回答3:


First you need to find the checked radio:

function getCheckedRadioId(name) {
    var elements = document.getElementsByName(name);

    for (var i=0, len=elements.length; i<len; ++i)
        if (elements[i].checked) return elements[i].value;
}

Then add the image to the checked element.

var img = document.createElement("img");
img.src = "http://www.google.com/intl/en_com/images/logo_plain.png";

var src = getCheckedRadioId(rgroup);
src.appendChild(img);
src.parentNode.insertBefore(img, src.nextSibling);


来源:https://stackoverflow.com/questions/18120815/add-class-to-radio-button

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