jQuery實現自訂checkbox和radio樣式,jquerycheckbox

來源:互聯網
上載者:User

jQuery實現自訂checkbox和radio樣式,jquerycheckbox

1,起因

最近在工作中要實現自訂式的radio樣式,而我們通常使用的時預設的樣式,因為自己實在想不到解決的方法,於是開始搜尋,最終看到了不錯的解決辦法,可以完美解決我們遇到的問題。

2,原理

大家都知道在寫結構的時候,radio或checkbox都會跟隨label一起使用,label的for屬性值和input的id值相同的情況下,點擊label就可以選中input,這裡正是利用label 來覆蓋我們的input預設樣式,通過給label添加背景圖片(美化的checkbox或radio),也就是在點擊的過程中,我們是看不到預設的input的(給input設定z-index:-1),而點擊的是label,通過不同的事件,載入不同的背景圖片(這裡是改變背景圖片的位置)

3,設定美化checkbox或radio的預設樣式

(1)頁面結構

<form class="form" method="post">  <fieldset>    <legend>Which genres do you like?</legend>    <input type="checkbox" value="action" id="check-1" name="genre"><label for="check-1" class="">Action / Adventure</label>    <input type="checkbox" value="comedy" id="check-2" name="genre"><label for="check-2" class="">Comedy</label>    <input type="checkbox" value="epic" id="check-3" name="genre"><label for="check-3" class="">Epic / Historical</label>    <input type="checkbox" value="science" id="check-4" name="genre"><label for="check-4" class="">Science Fiction</label>    <input type="checkbox" value="romance" id="check-5" name="genre"><label for="check-5" class="">Romance</label>    <input type="checkbox" value="western" id="check-6" name="genre"><label for="check-6" class="">Western</label>  </fieldset>   <fieldset>    <legend>Caddyshack is the greatest movie of all time, right?</legend>    <input type="radio" value="1" id="radio-1" name="opinions"><label for="radio-1" class="">Totally</label>    <input type="radio" value="1" id="radio-2" name="opinions"><label for="radio-2" class="">You must be kidding</label>    <input type="radio" value="1" id="radio-3" name="opinions"><label for="radio-3" class="">What's Caddyshack?</label>  </fieldset></form>

 (2)jquery code(前提必須引入jquery庫)

jQuery.fn.customInput = function(){  $(this).each(function(i){    if($(this).is('[type=checkbox],[type=radio]')){      var input = $(this);      //get the associated label using the input's id      var label = $('label[for='+input.attr('id')+']');      //get type,for classname suffix      var inputType = (input.is('[type=checkbox]')) ? 'checkbox' : 'radio';      //wrap the input + label in a div      $('<div class="custom-'+ inputType +'"></div>').insertBefore(input).append(input,label);      //find all inputs in this set using the shared name attribute      var allInputs = $('input[name='+input.attr('name')+']');      //necessary for browsers that don't support the :hover pseudo class on labels      label.hover(function(){        $(this).addClass('hover');        if(inputType == 'checkbox' && input.is(':checked')) {          $(this).addClass('checkedHover');        }      },function(){        $(this).removeClass('hover checkedHover');      });             //bind custom event, trigger it, bind click,focus,blur events      input.bind('updateState',function(){        if(input.is(':checked')){          if(input.is(':radio')){            allInputs.each(function(){              $('label[for='+$(this).attr('id')+']').removeClass('checked');            });          };          label.addClass('checked');        } else {          label.removeClass('checked checkedHover checkedFocus');        }      })      .trigger('updateState')      .click(function(){        $(this).trigger('updateState');      })      .focus(function(){        label.addClass('focus');        if(inputType == 'checkbox' && input.is(':checked')) {          $(this).addClass('checkedFocus');        }      })      .blur(function(){        label.removeClass('focus checkedFocus');      });            }  });}

 引入jquery庫,再引入上面的代碼後,就可以執行下面的代碼

$('input').customInput();

 (3)產生的外層div

如果你的代碼結構是label和input成對寫的話,那麼在它們的外層就會產生一個div,

(4)設定自訂預設樣式

準備好一張圖,如下:

你可能會問,為什麼上面沒有在頂端,而是有一定的距離,因為我們的input選項多是置中的,而我們是使用label的背景圖片來類比的,所以我們是為了讓input選項置中顯示。總之:ico小表徵圖一定要垂直排列,一定要留有一定的距離來達到置中顯示。

/* wrapper divs */      .custom-checkbox,      .custom-radio {        position: relative;        display: inline-block;      }      /* input, label positioning */      .custom-checkbox input,      .custom-radio input {        position: absolute;        left: 2px;        top: 3px;        margin: 0;        z-index: -1;      }      .custom-checkbox label,      .custom-radio label {        display: block;        position: relative;        z-index: 1;        font-size: 1.3em;        padding-right: 1em;        line-height: 1;        padding: .5em 0 .5em 30px;        margin: 0 0 .3em;        cursor: pointer;      }

 這是最外層的一些設定,當然你可以自己修改

/* ==預設狀態效果== */      .custom-checkbox label {         background: url(images/checkbox.gif) no-repeat;       }      .custom-radio label {         background: url(images/button-radio.png) no-repeat;       }      .custom-checkbox label,       .custom-radio label {        background-position: 0px 0px;      }
/*==滑鼠移至上方和得到焦點狀態==*/      .custom-checkbox label.hover,      .custom-checkbox label.focus,      .custom-radio label.hover,      .custom-radio label.focus {        /*background-position: -10px -114px;*/      }            /*==選中狀態==*/      .custom-checkbox label.checked,      .custom-radio label.checked {        background-position: 0px -47px;      }      .custom-checkbox label.checkedHover,      .custom-checkbox label.checkedFocus {        /*background-position: -10px -314px;*/      }      .custom-checkbox label.focus,      .custom-radio label.focus {        outline: 1px dotted #ccc;      }

結尾:總之,我是完美的解決了我的問題,順便發一個看看

以上所述就是本文的全部內容了,希望大家能夠喜歡。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.