하이브리드앱 웹뷰 마크업 진행 중 iOS UI 형태의 Checkbox on,off 스위치가 필요해 찾아 보니
Pure CSS 형태 또는 JS 스위치 동작이 목표 디바이스에서 만족스럽지 못해 직접 마크업 해봅니다.
미리보기
마크업 방향
- 모바일 환경 최적화를 위해 가능한 모든 효과는 CSS를 사용
- JS는 addClass(), removeClass() 정도만 사용
- click, touch 이벤트 (접근성 저하요인 밀기 동작은 제외)
- 아이폰 4,5,6 과 안드로이드 4.x 버전 이상 디바이스 지원
시작
padding, margin 에 영향을 받지 않도록 box-sizing 속성을 지정합니다.
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
HTML
스위치 label 태그는 position:relative; 속성의 부모 요소가 필요하기 때문에 div.wrap으로 한번 포장합니다.
CSS
액션 효과는 CSS 로만 처리하고자 Transition 속성을 지정하고 별도의 'on' 클래스를 작성합니다.
.wrap {
position: relative;
}
.wrap * {
-webkit-box-sizing: border-box;
-moz-box-sizing: border-box;
box-sizing: border-box;
}
/* iOS 타입 체크박스 토글 */
.wrap .i_toggle {
position: absolute;
top: 8px;
/*right: 14px;*/
display: inline-block;
width: 80px;
height: 34px;
font-weight: bold;
letter-spacing: 0;
}
.wrap .i_toggle > .chkbox {
position: absolute;
margin-left: -9999px;
visibility: hidden;
}
.wrap .i_toggle > .i_checked {
position: absolute;
/*overflow: hidden;*/
width: 100%;
height: 34px;
padding: 7px 10px;
-webkit-border-radius: 24px;
-moz-border-radius: 24px;
-ms-border-radius: 24px;
-o-border-radius: 24px;
border-radius: 24px;
font-size: 14px;
-webkit-box-shadow: 1px 1px 2px #999 inset;
box-shadow: 1px 1px 2px #999 inset;
-webkit-transition: all .5s ease;
-o-transition: all .5s ease;
transition: all .5s ease;
}
.wrap .i_toggle > .i_checked {
text-align: right;
background: #DFDFDF;
color: #666;
}
.wrap .i_toggle > .i_checked.on {
text-align: left;
background: #3897E1;
color: #fff;
}
.wrap .i_checked.on .stat span:after {
content: 'ON';
}
.wrap .i_checked .stat span:after {
content: 'OFF';
}
.wrap .i_toggle > .i_checked .ball {
position: absolute;
top: 2px;
left:2px;
width: 30px;
height: 30px;
/*border: 1px solid #ccc;*/
-webkit-border-radius: 15px;
-moz-border-radius: 15px;
-ms-border-radius: 15px;
-o-border-radius: 15px;
border-radius: 15px;
background: #fff;
-webkit-box-shadow: 1px 1px 2px #999;
box-shadow: 1px 1px 2px #999;
-webkit-transition: all .3s ease;
-o-transition: all .3s ease;
transition: all .3s ease;
}
.wrap .i_toggle > .i_checked.on > .ball {
left: 80px;
margin-left: -32px;
}
jQuery
animate, fadeIn 등의 jQuery 애니메이션 없이 간단히 addClass, removeClass 로 적용합니다.
$(function(){
// ios checkbox 스위치 토글
$('.i_toggle').on('click', function(e){
e.preventDefault();
var chkStat = $(this).find('.chkbox').is(':checked'); // 체크여부
if(!chkStat) {
$(this).find('.i_checked').addClass('on');
$(this).find('.chkbox').prop('checked', true);
} else {
$(this).find('.i_checked').removeClass('on');
$(this).find('.chkbox').prop('checked', false);
}
});
})
디바이스 체크
아이폰 4,5,6 과 안드로이드 4.1 버전(베가레이서, S3) 에서 무난히 적용되는군요.
버전별 전체 디바이스에서 테스트해보지 않았을 뿐..
fin.