JavaScript PR

JavaScriptでモーダル表示する方法【プラグイン、jQuery不使用】

記事内に商品プロモーションを含む場合があります

jQueryやJavaScriptプラグインを使用せず、モーダル表示する方法をご紹介します。
複雑な表示演出や切替等を行わず、シンプルにモーダル表示させたい時に使えます。

モーダル表示するCSSの記述

※モーダル表示エリア(#modal)のCSS記述です。必要に応じて書き換えてください。

<style type="text/css">
body{
  font-family:Verdana,"Hiragino Kaku Gothic Pro","ヒラギノ角ゴ Pro W6",Osaka,"MS Pゴシック",Arial,sans-serif;
  padding: 0;
  margin: 0;
  overflow-x: hidden;
  line-height: 1.8em;
  text-align: center;
}
h1{
  font-size:16px;
  text-align:center;
  font-weight:normal;
  padding:10px 0;
  position: relative;
}
#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.6);
}
.content{
  background-color:#ffffff;
  width: 500px;
  margin: 20% auto 0 auto;
  padding: 50px;
  text-align: center;
}
.content p{
  font-size: 20px;
  font-weight: bold;
  padding-bottom: 20px;
}
</style>

モーダル表示エリア・クリックボタンのHTML記述

※モーダル表示エリア(id=”modal”)とモーダル表示を行うクリックボタン(id=”bt”)を用意します。必要に応じて変更して下さい。

<h1>「モーダル表示」ボタンをクリックすると「モーダル表示エリア」が表示されます。</h1>

<div id="modal">
  <div class="content">
      <p>モーダル表示エリア</p>
      <input type="button" id="close" value="閉じる">
  </div>
</div>

<input type="button" id="bt" value='モーダル表示'>

モーダル表示するJavaScritpの記述

※「モーダル表示」ボタンクリックでモーダルエリアを表示し、「閉じる」ボタンクリックでモーダルエリアを非表示にします。

<script type="text/javascript">
var bt = document.getElementById('bt');
var modal = document.getElementById('modal');
var close = document.getElementById('close');

bt.addEventListener('click', function() {
  modal.style.display = 'block';
})
close.addEventListener('click', function() {
  modal.style.display = 'none';
})
</script>

jQueryを使用せずJavaScriptでモーダル表示するデモページ

jQueryを使用せずJavaScriptでモーダル表示するデモ

 
※流用される場合は自己責任でお願いします。
 タグ内のGoogleアナリティクスタグは流用しないで下さい。