こちら↓の記事を書いてから約2年。
【jQuery】簡単モーダルウィンドウ
もっと便利にと思い、ページ内に複数のモーダルウィンドウが設定できるように書き直してみました!
設定方法も簡単なので、ぜひ使ってみてください!!
HTMLでの記述方法
jQueryで関数mwを作成したので、この関数に引数を4つ設定すればページ内に複数のモーダルウィンドウを設定することができます!
関数に設定する4つの引数は以下の順番で設定してください。
mw(モーダル全体, モーダルのメインコンテンツ, 開くボタン , 閉じるボタン );
HTMLにJS、CSSをまとめて記述すると以下のようになります!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 | <! 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 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 > |