效果
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>