jQueryでモーダルをつかう方法
See the Pen AB-modal by abenosite (@abenosite) on CodePen.
index.html
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 |
<h1>モーダル</h1> <div class="modal-area"> <!-- モーダルのボタン --> <div class="modal-button">モーダル1を開く</div> <!-- モーダルのコンテンツ --> <div class="overlay"></div> <div class="modal-content"> <div class="modal-content-detail"> <div class="close">×</div> <h2>タイトル1が入ります。</h2> <p>テキストが入ります。テキストが入ります。テキストが入ります。</p> </div> </div> </div> <!-- /.modal-area --> <div class="modal-area"> <!-- モーダルのボタン --> <div class="modal-button">モーダル2を開く</div> <!-- モーダルのコンテンツ --> <div class="overlay"></div> <div class="modal-content"> <div class="modal-content-detail"> <div class="close">×</div> <h2>タイトル2が入ります。</h2> <p>テキストが入ります。テキストが入ります。テキストが入ります。</p> </div> </div> </div> <!-- /.modal-area --> |
style.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 |
.modal-area { width: 600px; margin: auto; } .modal-button { margin: 10px auto; background: #999; font-size: 16px; text-align: center; cursor: pointer; } .overlay { display: none; position: fixed; top: 0; left: 0; z-index: 1; width: 100%; height: 100%; background: rgba(0, 0, 0, 0.8); } .overlay.show-modal { display: block; } .modal-content { display: none; position: relative; justify-content: center; align-items: center; height: 100vh; position: absolute; top: 0; left: 0; width: 100vw; } .modal-content.show-modal { display: flex; } .modal-content-detail { padding: 20px; margin: auto; background: #fff; border-radius: 5px; position: relative; z-index: 2; width: 80%; max-width: 600px; } .modal-content .close { cursor: pointer; position: absolute; left: 20px; top: 10px; } |
script.js
1 2 3 4 5 6 7 8 9 |
$(function () { $('.modal-button').click(function () { $(this).nextAll('.modal-content').addClass('show-modal');//モーダルを開く $(this).nextAll('.overlay').addClass('show-modal');//オーバーレイを開く }) $('.overlay, .close').click(function () { $('.overlay, .modal-content').removeClass('show-modal');//モーダル、オーバーレイを閉じる }) }); |
以上で、モーダルをコピペで簡単に実装する方法でした。