JQuery統一複寫美化專案中所有radio單選按鈕樣式

Echoyya、發表於2020-12-12

老專案要升級改版,對於分散在各頁面的樣式不好處理,怕有遺漏,尤其是優化input表單,修改其預設樣式,接下來,我將給大家分享一下,我在專案中的總結。

效果

上程式碼:

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;
        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, 男男女女

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

相關文章