こちら↓の記事を書いてから約2年。
【jQuery】簡単モーダルウィンドウ
もっと便利にと思い、ページ内に複数のモーダルウィンドウが設定できるように書き直してみました!
設定方法も簡単なので、ぜひ使ってみてください!!
HTMLでの記述方法
jQueryで関数mwを作成したので、この関数に引数を4つ設定すればページ内に複数のモーダルウィンドウを設定することができます!
関数に設定する4つの引数は以下の順番で設定してください。
mw(モーダル全体, モーダルのメインコンテンツ, 開くボタン , 閉じるボタン );
HTMLにJS、CSSをまとめて記述すると以下のようになります!
<!DOCTYPE HTML>
<html lang="ja">
<head>
<meta charset="utf-8">
<title>モーダルウィンドウ</title>
<style type="text/css">
#modal{
display: none;
position: fixed;
z-index: 1;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgba(0,0,0,0.7);
}
#modal_content{
width:500px;
background:#fff;
margin:0;
padding:10px;
position:relative;
top: 50%;
left: 50%;
transform:translate(-50%,-50%);
}
#menu{
display: none;
position: fixed;
z-index: 1;
left: 0;
top: 0;
width: 100%;
height: 100%;
overflow: auto;
background-color: rgba(255,200,200,0.7);
}
#menu_content{
width:300px;
background:#faf;
margin:0;
padding:10px;
position:relative;
top: 50%;
left: 50%;
transform:translate(-50%,-50%);
}
</style>
</head>
<body>
<button id="btn_modal">モーダル表示</button>
<button id="btn_menu">メニュー表示</button>
<div id="modal">
<div id="modal_content">
<p>テキストテキストテキストテキストテキストテキストテキストテキストテキスト</p>
<p>テキストテキストテキストテキストテキストテキストテキストテキストテキスト</p>
<button class="btn_close">閉じる</button>
</div>
</div>
<div id="menu">
<div id="menu_content">
<p>テキストテキストテキストテキストテキストテキストテキストテキストテキスト</p>
<p>テキストテキストテキストテキストテキストテキストテキストテキストテキスト</p>
<button class="btn_close">閉じる</button>
</div>
</div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
<script type="text/javascript">
$(function(){
mw('#modal','#modal_content','#btn_modal','.btn_close');
mw('#menu','#menu_content','#btn_menu','.btn_close');
/*
mw(モーダル全体, モーダルのメインコンテンツ, 開くボタン , 閉じるボタン );
*/
});
function mw(modal, modalContent, btnOpen, btnClose){
$(btnOpen).on('click', function() {
$(modal).fadeIn();
});
$(modal).on('click', function(event) {
if(!($(event.target).closest($(modalContent)).length)||($(event.target).closest($(btnClose)).length)){
$(modal).fadeOut();
}
});
}
</script>
</body>
</html>






