JavaScriptとCSSを使って、モーダルウィンドウを作成します。
実現方法は至って単純で、なんらかのボタンが押されたらモーダルのdisplay属性をnoneにしたりblockにしたりするだけです。
.modal { display: none; position: fixed; z-index: 1; left: 0; top: 0; height: 100%; width: 100%; overflow: auto; background-color: rgba(0,0,0,0.5); } .modal-content{ background-color: white; width: 500px; margin: 40% auto; }
<!DOCTYPE html> <html> <head> <title>learn modal window</title> <link rel='stylesheet' href='style.css'> </head> <body> <h1>modal test!</h1> <input type='button' id='btn' value='click!'> <!--このdivタグ内がモーダルウィンドウ--> <div id='modal' class='modal'> <div class='modal-content'> <div class='modal-body'> <h1>this is modal!</h1> <input type='button' id='closeBtn' value='close'> </div> </div> </div> <script src='main.js'></script> </body> </html>
const btn = document.getElementById('btn'); const modal = document.getElementById('modal'); //ボタンを押した時に表示させる btn.addEventListener('click', function() { modal.style.display = 'block'; }) const closeBtn = document.getElementById('closeBtn'); //ボタンを押した時に非表示にする closeBtn.addEventListener('click', function() { modal.style.display = 'none'; })
単純なモーダルウィンドウになっているので、多少のスタイルの修正は必要ですが、手っ取り早くモーダルを実現したいのであればこれで十分でしょう。