モーダルウィンドウを作ってみる
2024.02.16 09:00
2024.02.16 12:41

モーダルウィンドウを作ってみます。
「Micromodal.js」というライブラリを使って実装します。
実装したデモはこちら
https://tech.exeweb.net/sample/3966
ライブラリの公式サイト
https://micromodal.vercel.app/
まずはHTMLから。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" media="all" href="modal.css" />
<title></title>
</head>
<body>
<!-- 開くボタン -->
<button class="modal__btn" data-custom-open="Modal" role="button">開く</button>
<!-- モーダルウィンドウ -->
<div id="Modal" class="modal" aria-hidden="true">
<div class="modal__overlay" tabindex="-1" data-custom-close>
<div class="modal__container" role="dialog" aria-modal="true" aria-labelledby="Modal-title" >
<div id="Modal-content" class="modal__content">
コンテンツ
<button data-custom-close>閉じる</button>
</div>
</div>
</div>
</div>
<script src="https://cdn.jsdelivr.net/npm/micromodal/dist/micromodal.min.js"></script>
<script src="https://polyfill.io/v3/polyfill.min.js?features=es6"></script>
<script src="modal.js"></script>
</body>
</html>
ライブラリはCDNで外部から読み込みます。
また、IE11に対応するようにpolyfillも一緒に読み込みます。
次にCSSです。
.modal {
display: none;
}
.modal.is-open {
display: block;
}
.modal__overlay {
position: fixed;
top: 0;
left: 0;
right: 0;
bottom: 0;
z-index: 2;
background: rgba(0,0,0,0.6);
display: flex;
justify-content: center;
align-items: center;
}
.modal__container {
background-color: #fff;
padding: 30px;
margin-right: 20px;
margin-left: 20px;
max-width: 640px;
max-height: 100vh;
width: 100%;
border-radius: 4px;
overflow-y: auto;
box-sizing: border-box;
}
.modal__close {
}
.modal__content {
margin-top: 2rem;
margin-bottom: 2rem;
line-height: 1.5;
}
そして最後にJavascript。
MicroModal.init({
openTrigger: 'data-custom-open', // モーダルを開くボタンに付ける
closeTrigger: 'data-custom-close', // モーダルを閉じるボタンにつける
openClass: 'is-open', // 開いたときにモーダルコンテナに付与するClass
disableScroll: true, // モーダルの後ろの画面のスクロールをさせるかどうか
disableFocus: true, // モーダル内にフォーカスパーツがある場合、モーダルが開いた瞬間にフォーカスさせるかどうか
awaitOpenAnimation: false, // 開くときのアニメーションを使うかどうか
awaitCloseAnimation: false, // 閉じるときのアニメーションを使うかどうか
debugMode: true // デバッグモードを表示するかどうか
});
細かく設定できるので使いやすいですね。
アニメーションなども反映できるみたいです。
今回は以上です!