以下は簡単な JavaScript モーダルのコード例です。

HTML コード:

<!--モーダルを開くボタン--> <button id="myBtn">モーダルを開く</button> <!--モーダル--> <div id="myModal" class="modal"> <!--モーダルの内容--> <div class="modal-content"> <span class="close">&times;</span> <p>モーダル内のテキスト...</p> </div> </div>

CSS コード:

/*モーダル(背景)*/ .modal { display: none; /*デフォルトで非表示*/ position: fixed; /*固定配置*/ z-index: 1; /*最前面に設定*/ left: 0; top: 0; width: 100%; height: 100%; overflow: auto; background-color: rgb(0,0,0); background-color: rgba(0,0,0,0.4); } /*モーダルの内容*/ .modal-content { background-color: #fefefe; margin: 15% auto; padding: 20px; border: 1px solid #888; width: 80%; } /*閉じるボタン*/ .close { color: #aaa; float: right; font-size: 28px; font-weight: bold; } .close:hover, .close:focus { color: black; text-decoration: none; cursor: pointer; }

JavaScript コード:

//モーダルを取得 var modal = document.getElementById('myModal'); //モーダルを開くボタンのオブジェクト var btn = document.getElementById("myBtn"); //<span> 要素を取得してモーダルを閉じる var span = document.querySelector('.close'); //ボタンをクリックしてモーダルを開く btn.onclick = function() { modal.style.display = "block"; } //<span>(x)をクリックしてモーダルを閉じる span.onclick = function() { modal.style.display = "none"; } //ユーザーが他の場所をクリックしたときにモーダルを閉じる window.onclick = function(event) { if (event.target == modal) { modal.style.display = "none"; } }

オンラインデモ


ヘッダーとフッターを追加したモーダル

HTML コード:

<!--モーダルを開くボタン--> <button id="myBtn">モーダルを開く</button> <!--モーダル--> <div id="myModal" class="modal"> <!--モーダルの内容--> <div class="modal-content"> <div class="modal-header"> <span class="close">&times;</span> <h2>モーダルのヘッダー</h2> </div> <div class="modal-body"> <p>モーダルのテキスト...</p> <p>モーダルのテキスト...</p> </div> <div class="modal-footer"> <h3>モーダルのフッター</h3> </div> </div> </div>

CSS コード:

/*モーダル(背景)*/ .modal { display: none; /*デフォルトで非表示*/ position: fixed; z-index: 1; padding-top: 100px; left: 0; top: 0; width: 100%; height: 100%; overflow: auto; background-color: rgb(0,0,0); background-color: rgba(0,0,0,0.4); } /*モーダルの内容*/ .modal-content { position: relative; background-color: #fefefe; margin: auto; padding: 0; border: 1px solid #888; width: 80%; box-shadow: 0 4px 8px 0 rgba(0,0,0,0.2),0 6px 20px 0 rgba(0,0,0,0.19); -webkit-animation-name: animatetop; -webkit-animation-duration: 0.4s; animation-name: animatetop; animation-duration: 0.4s } /*アニメーションを追加*/ @-webkit-keyframes animatetop { from {top:-300px; opacity:0} to {top:0; opacity:1} } @keyframes animatetop { from {top:-300px; opacity:0} to {top:0; opacity:1} } /*閉じるボタン*/ .close { color: white; float: right; font-size: 28px; font-weight: bold; } .close:hover, .close:focus { color: #000; text-decoration: none; cursor: pointer; } .modal-header { padding: 2px 16px; background-color: #5C8AB8; color: white; } .modal-body {padding: 2px 16px;} .modal-footer { padding: 2px 16px; background-color: #5C8AB8; color: white; }

オンラインデモ


下部に表示するモーダル