【簡単】モーダルウィンドウをCSS、jqueryで作る方法

モーダルウィンドウをプラグインを使わず、CSS、jqueryのみで簡単に再現したい!
このような疑問に回答します!
本記事ではプラグインを使わずに、CSS、jqueryでモーダルを作るやり方について、codepenデモを交えながら解説します。
codepenを使った実装例を紹介
See the Pen モーダルウィンドウ by Kohei (@kouk05) on CodePen.dark
上記がコードペンを使ったモーダルの実装例です。
【ここをクリック】を押すと、モーダルが展開され、背景・閉じるを押すとモーダルを閉じます。
とてもシンプルです。
上記実装例の詳細としては以下になります。
モーダルの内容をhtmlで書く
<span class="modal_open_btn">ここをクリック!!</span>
<div class="modal_contents">
<div class="modal_conte ents_wrap">
<!-- モーダルウィンドウの中身ここから -->
<p>モーダルウィンドウ</p>
<span class="modal_close_btn">閉じる</span>
</div>
</div>
</div>
まずはモーダルを開く、閉じるボタン(例ではテキスト)、モーダルの中身をhtmlで記述しましょう。
jqueryを使って、モーダル動作を作る
<script src="https://code.jquery.com/jquery-3.3.1.js"></script>
モーダルウィンドウを動作させるのにjqueryを使います。上記CDNをhead内等にコピペし、読ませときましょう。(すでに準備されてる方は必要ありません)
$(function() {
$('.modal_open_btn').on('click', function() {
$('.modal_contents').fadeIn();
return false;
});
$('.modal_close_btn').on('click', function() {
$('.modal_contents').fadeOut();
return false;
});
$('.modal_contents_bg').on('click', function() {
$('.modal_contents').fadeOut();
return false;
});
});
上記ソースを、script内にコピペしましょう。
クリック、閉じる、モーダルの背景のセレクタを指定、これらをクリックするとfadein(フェードイン)する、という内容になってます。
後はCSSで装飾するだけ
.modal_open_btn {
display: inline-block;
cursor: pointer;
padding-top: 30px;
}
.modal_contents {
display: none;
position: absolute;
top: 0;
left: 0;
z-index:100;
width: 100%;
height: 100%;
width: 100%;
}
.modal_contents_bg {
background: rgba(0,0,0,.8);
width: 100%;
height: 100%;
}
.modal_contents_wrap {
position: absolute;
top: 50%;
left: 50%;
background-color: #fff;
width: 50%;
height: 50%;
margin: auto;
transform: translate(-50%,-50%);
padding: 30px;
}
.modal_close_btn {
display: inline-block;
cursor: pointer;
margin-top: 10px;
}
後はCSSでモーダルを装飾するだけです!上記は参考例です。
以上でシンプルなモーダルウィンドウの完成になります。
まとめ
とてもシンプルなモーダルウィンドウですが、上記方法で実装出来ましたでしょうか?
シンプルなだけに書いてるソースもややこしくないので、自分好みに応用が効くと思います!
以上で解説を終わります。