checkbox
自定義控件概述
這個控件屬于html自帶的控件厨相,本身有樣式领曼。在制作這樣的控件時,需要CSS
和javascript
兩方面共同努力领铐,才能實現(xiàn)全新的控件樣式:CSS
覆蓋原有的樣式悯森、實現(xiàn)新的樣式;JS
實現(xiàn)點擊等動作的動態(tài)顯示绪撵。我們先看HTML結構瓢姻,再一步步看CSS
代碼。
radio
控件和checkbox
控件的定義方式也是一樣的流程音诈。下面是checkbox
的最終兩種效果圖:
HTML
代碼
<div class="input_custom">
<div class="custom-checkbox">
<input name="signup" type="checkbox" checked id="checkbox1" >
<label for="checkbox1" class="checked">Checked</label>
</div>
<div class="custom-checkbox">
<input name="signup" type="checkbox" id="checkbox2" >
<label for="checkbox2" >Unchecked</label>
</div>
<div class="checkbox-large">
<div class="custom-checkbox">
<input name="signup" type="checkbox" id="checkbox3" >
<label for="checkbox3" ></label>
</div>
</div>
<div class="checkbox-large">
<div class="custom-checkbox">
<input name="signup" type="checkbox" checked id="checkbox4" >
<label for="checkbox4" ></label>
</div>
</div>
</div>
input
的id
和label
的for
值需要設置幻碱,并且需要一致绎狭,主要用于后面的javascript
,在下文談到javascript
的時候再說褥傍。
CSS
代碼
-
設置
custom-checkbox
相對布局儡嘶,并且對瀏覽器自帶的checkbox
樣式進行處理。.custom-checkbox { position:relative;} .custom-checkbox input,.custom-radio input { display: none;}
-
全新的
custom-checkbox
主要是使用label來顯示文字恍风,并通過右移label蹦狂,把新的check-box樣式顯示出來,這里主要把新的custom-chekbox
用于label背景朋贬,我們看看是怎么做的凯楔,具體看代碼的注釋。.custom-checkbox label { display:block; //設置為塊級元素锦募,否則顯示會有問題 height:27px; line-height:27px; //通過行高和高度的設置摆屯,保證文字垂直居中 padding-left:36px; //將label的文字右移,為新的custom-chekbox樣式預留空間 margin-bottom:8px; cursor:pointer; //修改鼠標顯示樣式 color:#6f6f6f; }
-
放置新的
custom-checkbox
樣式糠亩,并依據(jù)是否選中虐骑,設置不同的background-position
,以顯示不同狀態(tài)下的custom-checkbox
赎线。.custom-checkbox label { background:url(images/styled_checkbox.png) no-repeat; background-position:-7px -10px; //custom-checkbox未選中狀態(tài) } .custom-checkbox label.checked { background-position:-7px -110px; //custom-checkbox選中狀態(tài) color:#5c5c5c; }
-
另一種樣式的
custom-checkbox
廷没。.checkbox-large .custom-checkbox label { background:url(images/styled_checkbox_large.png) no-repeat; height: 37px; line-height: 33px; padding-left:95px; background-position:0 0; //custom-checkbox未選中狀態(tài) } .checkbox-large .custom-checkbox label.checked { background-position:0 -100px; //custom-checkbox選中狀態(tài) }
javascript
代碼
javascript
代碼主要響應用戶的點擊。這里面使用了jquery
(或者更小的氛驮,通常移動端使用的腕柜,jquery替代版本——zepto.js
)。這里使用jquery
矫废,主要是因為方便。當然砰蠢,你也可以直接通過DOM
操作來實現(xiàn)這里的功能蓖扑,不過要稍微麻煩一些。
這里的javascript
的思路就是依據(jù)input的checked狀態(tài)台舱,動態(tài)地為label添加checked類或者移除checked類律杠。我們來看一下代碼:
$('div[class=input_custom] input').each(function(){ //選擇合適的input元素
if($(this).is('[type=checkbox],[type=radio]')){ //此處的代碼也適合自定義radio按鈕
var input = $(this);
var label = $('label[for='+input.attr('id')+']'); //還記得上面的html代碼嗎?此處就用到了input的id和label的for
input.bind('updateState', function(){
input.is(':checked') ? label.addClass('checked') : label.removeClass('checked'); })
.trigger('updateState')
.click(function(){ $('input[name='+ $(this).attr('name') +']').trigger('updateState'); });//綁定點擊事件
}
});