用jQuery實現自定checkbox效果

298885_2396915292080_744683301_n

checkbox在各加瀏覽器看的效果都不一樣,而且如果想要把checkbox改成自己想要的樣子,在css並沒有辦法直接支援,不過我們可以用css跟jquery搭配來做出我們想要的checkbox樣式。

首先先準備像上面的自己畫的圖片。

然後我們讓checkbox都看不到,再去加上自己要的樣子。
input[type="checkbox"]{
display:none;
}

接下來我們設定check跟uncheck該長什麼樣子。
.checked{
display:inline-block;
width:20px;
height:20px;
background:url(check.png);
}
.unchecked{
display:inline-block;
width:20px;
height:20px;
background:url(uncheck.png);
}

準備html如下

<span class="checkbox"><input type="checkbox" /></span>Check In
然後開始撰寫jQuery,先偵測讀完網頁後,checkbox的狀態,再去對應他應該要有的圖片。
if($(".checkbox").children("input").attr("checked")){
$(".checkbox").addClass("checked");
}else{
$(".checkbox").addClass("unchecked");
}

最後再把點擊後改變class跟checkbox狀態一併寫進jQuery就完成了。
$(".checkbox").click(function(){
if($(this).children("input").attr("checked")){
$(this).children("input").attr({checked: ""});
$(this).removeClass("checked");
$(this).addClass("unchecked");
}else{
$(this).children("input").attr({checked: "checked"});
$(this).removeClass("unchecked");
$(this).addClass("checked");
}
});


觀看效果

留言