hiroshi akutsuの日記

主にプログラミング関係のこと

select2【colorboxのモーダルウィンドウでselect2化したセレクトボックスがおかしくなる】

jqueryのcolorboxはライセンスもMITで非常に人気のあるプラグインです。
またselect2も同じくMITライセンスで非常に高機能なUIを提供してくれるいいプラグインです。

モーダルウィンドウをcolorboxで表示して、その中でプルダウンをselect2化したときに、ほとんどのブラウザで動かなくなると思います。
なかなか情報探すのに苦労しましたが、わかってしまえば結構簡単に解決できたので、メモを残します。

環境

・クライアントPC:windows 10
・ブラウザ:IE11、Edge、Firefoxchrome
・サーバ:centos7、apache2.4
jquery:1.10.2
・colorbox:1.6.4
・select2:4.0.3

以下サンプルです。colorboxのパスは適当に読み替えてください。
select2を実行するときに、

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>colorbox and select2</title>
	<script src="//ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
	<link rel="stylesheet" type="text/css" href="colorbox/colorbox-master/example3/colorbox.css"/>
	<script type="text/javascript" src="colorbox/colorbox-master/jquery.colorbox.js"></script>
	<link href="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/css/select2.min.css" rel="stylesheet" />
	<script src="//cdnjs.cloudflare.com/ajax/libs/select2/4.0.3/js/select2.min.js"></script>
	<script type="text/javascript">
		$(function(){
			var $colorboxArea = $("div.colorboxArea");
			$(":button.open_cb").colorbox({
				inline : true,
				href : $colorboxArea,
				innerWidth : "80%",
				innerHeight : "80%"
			});
			$("select.target").select2({
				dropdownParent: $(".colorboxArea")
			});
		});
	</script>
	<style type="text/css">
		/*IEは以下のように書かないとwidthが0になる*/
		.select2{
			min-width:200px;
		}
	</style>
</head>
<body>
	<input type="button" class="open_cb" value="show modal window!">
	<div style="display:none;">
		<div class="colorboxArea">
			<select class="target">
				<option value="1">aaa</option>
				<option value="2">bbb</option>
			</select>
		</div>
	</div>
</body>
</html>

といったようにdropdownParentプロパティを指定します。
値は、colorboxの領域を指定します。

IEに対応するためにはwidthをスタイルシートで指定する必要がありますが、これで正常に表示できます。