Blog

【jQuery】モーダルウインドウの実装方法

2017/04/23

JQuery

備忘録です。

先日、colorboxを使ったモーダルウィンドウについて書きましたが、今回はcolorboxを使わない方法です。

参考サイト
画面中央に表示するモーダルウィンドウを実装したい

HTML

<div id="modal-main">モーダルウィンドウ</div>
 
<!-- #contents START -->
  <div id="contents">
    <p><a id="modal-open">【クリックでモーダルウィンドウを開きます。】</a></p>
    <p class="page-txt">ここからページ本文<br>
    <br>
    ↓↓↓ スクロールしてください ↓↓↓</p>
  </div>
<!--/#contents-->

CSS

#contents {
  z-index: 0;
  font-size: 16px;
}
.page-txt {
  margin: 30px 0 0;
  height: 2000px;
}
#modal-open {
  color: #cc0000;
}
/* モーダル コンテンツエリア */
#modal-main {
  display: none;
  width: 500px;
  height: 300px;
  margin: 0;
  padding: 0;
  background-color: #ffffff;
  color: #666666;
  position:fixed;
  z-index: 2;
}
/* モーダル 背景エリア */
#modal-bg {
  display:none;
  width:100%;
  height:100%;
  background-color: rgba(0,0,0,0.5);
  position:fixed;
  top:0;
  left:0;
  z-index: 1;
}

JS

//modal
$(function(){
 
  //テキストリンクをクリックしたら
 $("#modal-open").click(function(){
      //body内の最後に<div id="modal-bg"></div>を挿入
     $("body").append('<div id="modal-bg"></div>');
 
    //画面中央を計算する関数を実行
    modalResize();
 
    //モーダルウィンドウを表示
        $("#modal-bg,#modal-main").fadeIn("slow");
 
    //画面のどこかをクリックしたらモーダルを閉じる
      $("#modal-bg,#modal-main").click(function(){
          $("#modal-main,#modal-bg").fadeOut("slow",function(){
         //挿入した<div id="modal-bg"></div>を削除
              $('#modal-bg').remove() ;
         });
 
        });
 
    //画面の左上からmodal-mainの横幅・高さを引き、その値を2で割ると画面中央の位置が計算できます
     $(window).resize(modalResize);
      function modalResize(){
 
            var w = $(window).width();
          var h = $(window).height();
 
            var cw = $("#modal-main").outerWidth();
           var ch = $("#modal-main").outerHeight();
 
        //取得した値をcssに追加する
            $("#modal-main").css({
                "left": ((w - cw)/2) + "px",
                "top": ((h - ch)/2) + "px"
          });
     }
   });
});

スマホなどでモーダルウィンドウがはみ出す場合には、下記を追加することでスクロールできます。

#modal-main{
    max-height: 100vh;
    overflow:auto;
}

カテゴリー

月間アーカイブ

MORE

ミュージシャンズ・プラザ

神社仏閣ホームーページ制作

ホームページ制作問合せ