效果
css
.custom-radio { float: left; } .custom-radio input { position: absolute; left: -9999px; vertical-align: middle; } .custom-radio label { cursor: pointer; padding-right: 20px; line-height: 30px; padding-left: 25px; position: relative; display: inline-block; } .custom-radio label:hover { color: #FF6200; } .custom-radio label::after { content: ''; display: block; position: absolute; top: 6px; left: 0; width: 16px; height: 16px; outline: 0; border: 1px solid #D5D5D5; border-radius: 50%; } .custom-radio label.checked::after { border: 6px solid #FF6200; width: 6px; height: 6px; } .custom-radio label, .custom-radio label.checked { border: none; background: none; }
2.簡單搞一搞 HTML, 男男女女jquery
<input type="radio" name="yesOrNo" id="yes" checked /> <label for="yes">是</label> <input type="radio" name="yesOrNo" id="no" /> <label for="no">否</label>
定義一個JQuery的擴展方法,頁面加載完畢,input radio循環調用優化
建立一個新的Div,並設置類名,用於定義cssthis
使用輸入的ID獲得相關的標籤,將input radio及對應的id的label,放進上述Div中code
綁定自定義事件,觸發它,綁定點擊,焦點等事件blog
<script src="./jquery-1.11.1.min.js"></script> <script> $.fn.customInput = function () { return $(this).each(function () { if ($(this).is('[type=radio]')) { var input = $(this); var label = $('label[for=' + input.attr('id') + ']'); label.add(input).wrapAll('<div class="custom-' + input.attr('type') + '"></div>'); label.hover = function () { $(this).addClass('hover'); }; input.bind('updateState', function () { input.is(':checked') ? label.addClass('checked') : label.removeClass('checked'); }) .click(function () { $('input[name=' + $(this).attr('name') + ']').trigger('updateState'); }) .focus(function () { // 自定義處理邏輯 label.addClass('focus'); if (input.is(':checked')) $(this).addClass('checkedFocus'); }) .blur(function () { // 自定義處理邏輯 label.removeClass('focus checkedFocus'); }); } }); }; $('input:radio').each(function () { var $this = $(this); $this.customInput(); //初始化單選框 }); </script>