Quantcast
Channel: CSSタグが付けられた新着記事 - Qiita
Viewing all articles
Browse latest Browse all 8695

jQueryでさくっとモーダルウィンドウを作る

$
0
0

さくっとモーダルウィンドウを作ります。プラグイン不要です。

HTML

まずは骨組みのHTML。作るのは

  • モーダルウィンドウを開くためのリンク
  • モーダルウィンドウそのもの
  • 背景

の3つです。

HTML
<!-- modal open --><aclass="js-modal-open"href=""data-target="modal01">モーダルウィンドウを開く</a><!-- ./modal open --><!-- modal --><divid="modal01"class="c-modal js-modal"><divclass="c-modal_bg js-modal-close"></div><divclass="c-modal_content _lg"><divclass="c-modal_content_inner">ここにモーダルウィンドウの内容が入ります
            <aclass="js-modal-close c-modal_close"href=""><span>閉じる</span></a></div></div></div><!-- ./modal -->

ポイントはIDとdata-target属性の値を同じものにすること。
1ページで複数のモーダルウィンドウを開きたいときは、IDとdata-targetの値をmodal02のように別にして用意する。

Sass

CSSを使ってスタイリングします。sassで書いています。

Sass
// モーダルウィンドウ全体のレイアウト(画面いっぱいに表示).c-modal{display:none;height:100vh;position:fixed;top:0;width:100%;top:0;left:0;z-index:1;}// 黒背景の設定.c-modal_bg{background:rgba(0,0,0,0.6);height:100vh;width:100%;}// ウィンドウの設定.c-modal_content{background:#fff;left:50%;position:absolute;top:50%;transform:translate(-50%,-50%);border-radius:5px;&._sm{width:30%;}&._md{width:50%;}&._lg{width:70%;}}.c-modal_content_inner{position:relative;padding:24px;}// 閉じるボタン.c-modal_close{position:absolute;top:13px;right:10px;}

&._smとか&._mdとか&._lgというのはウィンドウのサイズ設定で使っています。
サイズ変更が不要であれば.c-modal_content内にwidthを設定してもいいと思います。

jQuery

最後に動きをつけます。

jQuery
// ウィンドウを開く$('.js-modal-open').each(function(){$(this).on('click',function(){vartarget=$(this).data('target');varmodal=document.getElementById(target);$(modal).fadeIn(300);returnfalse;});});// ウィンドウを閉じる$('.js-modal-close').on('click',function(){$('.js-modal').fadeOut(300);returnfalse;});

.c-modal_bgコンテンツにも.js-modal-closeを付与することで、背景をクリックしてもウィンドウが閉じる(フェードアウトする)ようになります。

完成形

こちらが完成形です。

See the Pen jQuery - ModalWindow by nagomi-753 (@nagomi-753) on CodePen.

以上です。


Viewing all articles
Browse latest Browse all 8695

Latest Images

Trending Articles

<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>