您所在的位置:小祥子 » 编程 » CSS » 正文

自定义表单样式之checkbox和radio

时间:2015-07-12 编辑:诚人小李 来源:CnBlogs

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,如图

JS9fevvvt28++vv3r51ZcvvvxsvXq++uRpnP82grvklwtijBgjXvKf5MSMDTz1X+VMcOZu0VWQU8bOGTvPxMZMNBdwtSNqXpOLS5XCSlZ2UnQWxs4Zu4z6fKqVZkNVxZJXLRZZcY1K0ZozFrhG5EQ5ZYyyjFhGPKsKb6ydJHFBGQvY0SzETVH8l1PGiGWUR8qxWmj0lkqvp8ux344AAACkgm03L5mN508/ivKf7/zllJXnfNxcPG3HQ3Aq1vXY6lmVbFOsueDmC17Qnr5mI4TjkbgpSfyXi5LAtAulFdApOQm/9bbLlYtKbZ5RTiQ5ibz4NxckcuKsYk3FUsHaCwIj4txuT2nNQK7yD6GbZJZT1uW0UDdbd1IN4AICAHAsYGrD84t/LD/72+O/P/vT8vHDJ/M/t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NQy2dBYprUi0z/+CLTft5urrNyDF+Yu30Oxrywf1bBtrT1ivLc23dLOM9L7XazFT+9r1Nffx/gMkLiPgPwgEYkuLvYRbKMetHeQWCfgPAoFAIKcoB+W/X+D7nxAIBAIZhyD+AwQCgUBOUQaI//ezXw+vNgQCgUBOXBD/HQAAADhFdMp/+ULILssDAAAAgJ6wK//li4yvnDQpFrn1f2KMNCHmghhvVyAAAAAA9ISd+C9fZJlNdRR2/iSnFg6hnDJQIAAAAHAQtOe/IPkRST71qa4d/xEoEAAAADgQ2vLfRvAA+VG+4GJT/U8QY8QY8ZL/JCfGiJdkqP4rciIizigTRlFyynGICAAAAPSMlvwXcf5ysag4K6esPOfjxvkfSTKJTXBS5UiH7eACAgAAAP2jk/3PlTCcP5PnrP1Pm/9IEuOUCycR5AcAAAAcAh08/2I5f5Tq/6lfWUYVlYL8AAAAgENh//cfbOdP/Wic/6l3HtSBH2PWKxCW84f3HwAAAIADYt/333MxFYHnYQAAAABg1MD3zwAAAIBTBPgPAAAAOEWA/wAAAIBTxP8B5/7iT7mdXtwAAAAASUVORK5CYII=" border="0" onload="return imgzoom(this,600);"/>

(4)设置自定义默认样式

准备好一张图,如下:

PHP+KN7fl7whDso7ug+3/bmNP6Yd1rcHV7fxUvDqIlZj3J0/DkvL/gosVy60w/W9Nyu8ce500IpdXd4fRst6GFPuJMIUlS8fqtp/JF3WlxePJ3ijXCjVPgj77QoM/7IOy3Khs+O+SPvtMjiCzzmD5ztj7zTIsU/O9sX61V34HteHXWnhf6de3al468W9T2fXeF1g8ZgMFBKXV05e6v5SRB7+kKD0TstbjU/md28FPOg5db7wZpLdwq5wtNrez3sdc+3abuL789uXjpwba9zdvMS5WgQbek+nw74gq3t9a6OcpQ+/LY3N4yaXNIxfxXzYBBtbaMFvbDXu7ribWlH9/O94I7ez9+zK3eH10fznl1pufVdvNQP1kzSwqxHuLO/pSsYPlO9036btgfRVj9Ye+Iv6ykwm7t4qeOv9oO1YdS0aTuV68desErOM9XLKLF8Zugm0GW8QbRlhBs6B9FWWsBDccdnRiovZA1v1E85ihIrW8DNpi7dhslQ17CLXr191q/r9tnSfTYPKNpPdG6RK7waPbHROXpWo3OfXfwTm6ea4JfjugNP7NIfleus7uCGeBFHtIXAv8AAPOABD3jAAx7wgAc84AEPeMAfD//q5CuN/x/t+QXpVZyr7QAAAABJRU5ErkJggg==" border="0" onload="return imgzoom(this,600);"/>

你可能会问,为什么上面没有在顶端,而是有一定的距离,因为我们的input选项多是居中的,而我们是使用label的背景图片来模拟的,所以我们是为了让input选项居中显示。总之:ico小图标一定要垂直排列,一定要留有一定的距离来达到居中显示。

CSS;gutter:true;">/* 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;
            }
View Code
/*==鼠标悬停和得到焦点状态==*/
            .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;
            }
View Code

结尾:总之,我是完美的解决了我的问题,顺便截图发一个看看

参考来源:

美化表单——自定义单选按钮和复选按钮(个人推荐)

美化表单

关键词:定义 表单 样式