JQuery统一复写美化项目中所有radio单选按钮样式

老项目要升级改版,对于分散在各页面的样式不好处理,怕有遗漏,尤其是优化input表单,修改其默认样式,接下来,我将给大家分享一下,我在项目中的总结。

本文为Echoyya、所创,转载请带上原文链接,感谢 https://www.cnblogs.com/echoyya/p/14126709.html

效果

上代码:

1.简单搞一搞 CSS,此处代码有折叠,Click Me~

    .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;
         16px;
        height: 16px;
        outline: 0;
        border: 1px solid #D5D5D5;
        border-radius: 50%;
    }
    .custom-radio label.checked::after {
        border: 6px solid #FF6200;
         6px;
        height: 6px;
    }
    .custom-radio label,
    .custom-radio label.checked {
        border: none;
        background: none;
    }

2.简单搞一搞 HTML

 <input type="radio" name="yesOrNo" id="yes" checked />
 <label for="yes">是</label>
 <input type="radio" name="yesOrNo" id="no" />
 <label for="no">否</label>

3.开整 ~~~~

首先分析一下实现思路:

  • 定义一个JQuery的扩展方法,页面加载完毕,input radio循环调用

  • 创建一个新的Div,并设置类名,用于定义css

  • 使用输入的ID得到相关的标签,将input radio及对应的id的label,放进上述Div中

  • 绑定自定义事件,触发它,绑定点击,焦点等事件

<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>
原文地址:https://www.cnblogs.com/echoyya/p/14126709.html