本篇博客介紹如何在單選按鈕選中時更改被選中的單選按鈕樣式
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; width: 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; /*融合行內於塊級*/ width: 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; width: 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!