jQueryとCSSで作るiPhone風ラジオボタン・チェックボックス
いつも使っているラジオボタンやチェックボックスにもっと彩りを!ここではCSSとjQueryを使ってiPhone風のデザインに変える方法を紹介します。使用する画像は一枚のみ。CSSスプライトで表示位置を変えます。サンプルも用意してみたので覗いてみてくださいね!

サンプルはこちら。IE7, IE8, FF, Chromeで正常動作
ファイルを準備
必要なファイルを準備します
コーディング
ファイルを読み込む
ヘッダー内にjQueryを読み込ませます。
<script type='text/javascript' src='/sample/js/jquery.js'></script>
HTML
<p class="field switch"> <input type="radio" id="radio1" name="field" checked /> <input type="radio" id="radio2" name="field" /> <label for="radio1" class="cb-enable selected"><span>Enable</span></label> <label for="radio2" class="cb-disable"><span>Disable</span></label> </p> <br /><br /> <p class="field switch"> <label class="cb-enable"><span>On</span></label> <label class="cb-disable selected"><span>Off</span></label> <input type="checkbox" id="checkbox" class="checkbox" name="field2" /> </p>
JavaScript
jQueryでラジオボタンやチェックボックスが選択されたときにクラスを加え、背景画像の表示位置を変更します。
$(document).ready( function(){
$(".cb-enable").click(function(){
var parent = $(this).parents('.switch');
$('.cb-disable',parent).removeClass('selected');
$(this).addClass('selected');
$('.checkbox',parent).attr('checked', true);
});
$(".cb-disable").click(function(){
var parent = $(this).parents('.switch');
$('.cb-enable',parent).removeClass('selected');
$(this).addClass('selected');
$('.checkbox',parent).attr('checked', false);
});
});
CSS
CSSスプライト使用のため、背景画像の表示位置が重要。
.cb-enable, .cb-disable, .cb-enable span, .cb-disable span { background: url(/sample/images/switch.gif) repeat-x; display: block; float: left; }
.cb-enable span, .cb-disable span { line-height: 30px; display: block; background-repeat: no-repeat; font-weight: bold; }
.cb-enable span { background-position: left -90px; padding: 0 10px; }
.cb-disable span { background-position: right -180px;padding: 0 10px; }
.cb-disable.selected { background-position: 0 -30px; }
.cb-disable.selected span { background-position: right -210px; color: #fff; }
.cb-enable.selected { background-position: 0 -60px; }
.cb-enable.selected span { background-position: left -150px; color: #fff; }
.switch label { cursor: pointer; }
.switch input { display: none; }
意外と簡単にできあがりました :)
参照サイト: DEV GROW

Pingback: 14時のヘッドライン | CROSS SBM
Pingback: とっても! ちゅどん(雑記帳) » Blog Archive » jQueryとCSSで作るiPhone風ラジオボタン・チェックボックス | Webクリエイターボックス
Pingback: 今日のブログ 04月02日 « 今日のiPhone/iPod touchのブログ
Pingback: freewebdev.jp