jQuery 簡単にモーダルウィンドウを実装する方法 (プラグイン不要)

この記事は年前に書かれました。不適当な記述を含む場合がありますので、参考程度に留めてください。

どうもこんばんは。今回は【簡単にモーダルウィンドウを実装する方法 (プラグイン不要)】というネタです。モーダルウィンドウ?という方もいるかと思いますので別の言い方をするとポップアップで小窓が出てくる表現の事を指します。実装方法はとても簡単ですので機会がありましたらお試しください。

コード(2013/4/11更新しました)

基本的には下図の用な仕様になっております。表示するコンテンツを増やす場合にはコピー&ペーストでwd2,wd3…と任意の数にしてください。

jQuery

$(function(){
$(‘.btns’).click(function(){
wn = ‘.’ + $(this).data(‘tgt’);
var mW = $(wn).find(‘.modalBody’).innerWidth() / 2;
var mH = $(wn).find(‘.modalBody’).innerHeight() / 2;
$(wn).find(‘.modalBody’).css({‘margin-left’:-mW,’margin-top’:-mH});
$(wn).fadeIn(500);
});
$(‘.close,.modalBK’).click(function(){
$(wn).fadeOut(500);
});
});
HTML
<div class="modal wd1">
<div class="modalBody">
<p class="close">×close</p>
<p>…..</p>
</div>
<div class="modalBK"></div>
</div>

<div class="modal wd2">
<div class="modalBody">
<p class="close">×close</p>
<p>…..</p>
</div>
<div class="modalBK"></div>
</div>

<div class="modal wd3">
<div class="modalBody">
<p class="close">×close</p>
<p>…..</p>
</div>
<div class="modalBK"></div>
</div>

<p data-tgt="wd1" class="btns">1</p>
<p data-tgt="wd2" class="btns">2</p>
<p data-tgt="wd3" class="btns">3</p>

基本CSS
.modal{display:none;}
.modalBody{position: fixed; z-index:1000; background: #000; width:690px; left:50%; top:50%; height: 400px}
.modalBK{position: fixed; z-index:999; height:100%; width:100%;background:#000; opacity: 0.9;filter: alpha(opacity=90);-moz-opacity:0.90;}
装飾CSS

割愛していただいてかまいません。

.btns{font-size: 80px; width:150px; background:#111; height: 150px; line-height:150px; text-align:center; font-family: arial; color: #fff; float: left; margin:10px; cursor: pointer}
.close{cursor: pointer;}
.modal{width:690px; color: #eee;}
.modal p{font-size:12px; text-align:justify;}
.modal h1{font-weight:bold; font-size: 30px;}
.modalBody{padding: 10px;}

以上になります。