CSS设置单选按钮选中样式

本篇博客介绍如何在单选按钮选中时更改被选中的单选按钮样式

html代码:

<div class="div_radio">
    <div class="div_radio_left">
        <input type="radio" name="sexradio" checked="checked" value="1" id="radio-1" />
        <label for="radio-1" class="radio-label">男</label>
    </div>
    <div calss="div_radio_right">
        <input type="radio" name="sexradio" value="0" id="radio-2">
        <label for="radio-2" class="radio-label" style="color: #666666;">女</label>
    </div>
</div>

CSS代码:

<style type="text/css">
    .div_radio_left {
        float: left;
        text-align: left;
         50%;
    }

    .div_radio_right {
        float: left;
        text-align: right;
    }

    input[type="radio"] {
        position: absolute; /*绝对定位*/
        clip: rect(0,0,0,0); /*裁剪图像*/
    }

    .div_radio label {
        display: inline-flex; /*将对象作为内联块级弹性伸缩盒显示*/
        flex-direction: row; /*主轴为水平方向,起点在左端*/
        align-items: center; /*垂直居中*/
    }

    /*紧邻lable标签的单选按钮创建伪元素*/
    input[type="radio"] + label::before {
        content: ''; /*插入内容为空*/
        display: inline-block; /*融合行内于块级*/
         10px;
        height: 10px;
        border-radius: 10px; /*设置圆角*/
        border: 1px solid #666666;
        margin-right: 3px;
    }

    /*紧邻lable标签选中的单选按钮创建伪元素*/
    input[type="radio"]:checked + label::before {
        background-clip: content-box; /*背景裁剪到内容框*/
        background-color: #BB1E19;
         6px;
        height: 6px;
        padding: 2px;
        border: 1px solid #BB1E19;
    }
</style>

JS代码:

<script type="text/javascript">
    $(function () {
        //点击单选按钮
        $(":input[name='sexradio']").click(function () {
            if (Number($(this).val()) == 1) {
                $(this).parent().parent().find("div").eq(0).find("label").eq(0).css("color", "#BB1E19");
                $(this).parent().parent().find("div").eq(1).find("label").eq(0).css("color", "#666666");
            }
            else {
                $(this).parent().parent().find("div").eq(1).find("label").eq(0).css("color", "#BB1E19");
                $(this).parent().parent().find("div").eq(0).find("label").eq(0).css("color", "#666666");
            }
        })
    })
</script>

效果图:

End!

原文地址:https://www.cnblogs.com/gygg/p/12160319.html