我正在使用CSS设置我的inputtype= radio的样式,因为我需要用一个图像替换默认的radio。实际上我所做的是隐藏输入元素,并显示带有图像背景的样式标签。
为此,我使用了新的CSS3选择器"#myinputradio + label“和"myinputradio:checked + label”。使用每个浏览器的最新版本(包括IE9)都能很好地工作,但我需要让它在IE7上工作。
我也可以参考JQuery,但我想在JS和支持CSS3的浏览器上使用相同的CSS选择器(我有很多单选输入,每个输入都有自己的背景图像,由一个普通的sprite放置)。
有没有办法也支持更老的浏览器呢?
下面是一个来自HTML的示例:
<input id="euro" type="radio" value="euro" checked="" name="currency">
<label for="euro"></label>下面是用来设置样式的CSS:
#euro + label /*and all other checkboxes*/ {
    display: inline-block;
    width: 37px;
    height: 37px;
    background: url(../img/sprites.png);
}
#euro + label {
    background-position: 1042px 898px;
}
#euro:checked + label {
    background-position: 1108px 898px;
}如果你需要更多的信息,请问我。谢谢。
发布于 2011-09-18 22:22:12
这应该可以很好地工作(小提琴:http://jsfiddle.net/p5SNL/):
//Loops through each radio input element
$('input[type="radio"]').each(function(){
    // Checks if the next element is a label, and whether the RADIO element 
    //  has a name or not (a name attribute is required)
    if(/label/i.test($(this).next()[0].tagName) && this.name){
        // Adds an onchange event handler to the RADIO input element
        // THIS FUNCTION will ONLY run if the radio element changes value
        $(this).change(function(){
            // Loop through each radio input element with the a name attribute
            //  which is equal to the current element's name
            $('input[type="radio"][name="'+this.name+'"]').each(function(){
                /*****
                 * The next line is an efficient way to write:
                 * if(this.checked){ // Is this element checked?
                 *     // Adds "labelChecked" class to the next element (label)
                 *     $(this).next().addClass("labelChecked");
                 * } else {
                 *     //Removes "labelChecked" class from next element (label)
                 *     $(this).next().removeClass("labelChecked");
                 * }
                 *****/
                $(this).next()[this.checked?"addClass":"removeClass"]("labelChecked");
                /* Alternatively, setting the CSS background:
                 * CSS background = IF "radio checked?" THEN "green" ELSE "red"
                $(this).next().css("background", this.checked?"green":"red");
                 */
            });
        }); //end of event handler declaration
        //Adds "labelChecked" class to the current element IF it's checked
        if(this.checked) $(this).next().addClass("labelChecked");
        /*Alternative way, setting a CSS background instead of a className:
        if(this.checked) $(this).next().css("background", "green");
         */
    } //end of IF
}); //end of the loop through all RADIO elements请注意,我故意在最后一个label (小提琴)添加了错误的for属性,以显示在将错误的for属性附加到标签时会发生什么(以及应该发生什么)。
编辑
阅读注释以获得代码的解释。我添加了另一种方式来定义注释中的样式(2x)。
https://stackoverflow.com/questions/7461756
复制相似问题