実験室

チェックボックスと画像を連動させる。(IE向け)

サンプル

コード

<p id="output">
<label for="input1"><input type="checkbox" id="input1" name="a" value="1"><img src="input1/img.png" width="50" height="50">text</label>
<label for="input2"><input type="checkbox" id="input2" name="a" value="1"><img src="input2/img.png" width="50" height="50">text</label>
<label for="input3"><input type="checkbox" id="input3" name="a" value="1"><img src="input3.png" width="50" height="50">text</label>
</p>
<script>(function($){
	
	$.fn.dabilabel = function(on_postfix, over_postfix, absurl){
	
	on_postfix = ( on_postfix==undefined||on_postfix===false )? "_on": on_postfix;
	over_postfix = ( over_postfix==undefined||over_postfix===false )? "_over": over_postfix;
	
	return this.each(function(key, value){
	var $this = $(this);
	
	var off_image = $this.attr('src');
	// queryを退避
	var query = off_image.match(/\?|#.*$/) || '';
	off_image = off_image.replace(/\?|#.*$/);
	
	var on_image = absurl? on_postfix: off_image.replace(/(\.[^.]+)$/, on_postfix+"$1");
	var over_image = absurl? over_postfix: off_image.replace(/(\.[^.]+)$/, over_postfix+"$1");
	
	var images = [off_image+query, on_image+query, over_image+query];
	var $label = $this.closest('label');
	//console.log(images);
	$.each(images, function(index, item){$('<img>').attr('src', item);});
	$this.data('dabimgsrc', images);
	
	$("#"+$label.attr('for')).on("click", function(e){
	$this.attr("src", $this.data('dabimgsrc')[+this.checked]);
	});
	
	$this.click(function(e){
	if( /MSIE/.test(navigator.userAgent) && (/MSIE (\d)/)[1]<9){
	$("#"+$label.attr('for')).click();
	}
	});
	
	$this.mouseover(function(e){
	var $img = $(this);
	//console.log($img.data('dabimgsrc'));
	$img.attr("src", $img.data('dabimgsrc')[2]);
	})
	.mouseout(function(e){
	var $img = $(this);
	$img.attr("src", $img.data('dabimgsrc')[+$img.siblings('input').prop("checked")] );
	})
	.mouseout(); // onload-cache
	
	return $this;
	});
};

})(jQuery);

// usage
$(function(){$("#output label img").dabilabel();});
</script>